by remram · 4y ago · 0 comments
v1 = tuple(map(int, v1.split('.')))
v2 = tuple(map(int, v2.split('.')))
return (v1 > v2) - (v1 < v2)
(In Python 2 days, the last line could have been `return cmp(v1, v2)`, but sadly cmp() and .__cmp__() were removed in Python 3.)And both of these implementations demonstrate an advantage of using someone else’s library: it has probably had more care put into it. And implementing these sorts of things yourself often leads you to compromise on functionality—though at the same time, using a misfitting library also leads to compromises. It can always go both ways.
For the specific use-case the OP had, the sorts of comparisons you're doing are unnecessary, so a custom-tuned compare is faster.
(I’m not speaking for BYO or library philosophies, merely describing considerations and caveats of both.)
Personally I mostly wanted to offer a warning to somebody else who might take this code.
I'm absolutely not saying that you should have used a library, but pointing out the other side of the problem. If they had used an existing library to handle the versions, it wouldn't have had this issue. And test cases wouldn't help here because if they didn't think to code for multiple digits in the second spot, they likely wouldn't have thought to test for it.
There's enough benefits and drawbacks to library vs roll-your-own that I don't rigidly stick to one way or the other.
Also good sweng practices would dictate to put it in one function that is used in all places so you only need to fix it once.