Version Number Comparison Function

Bengt Richter bokr at oz.net
Fri Mar 25 14:23:37 EST 2005


On Fri, 25 Mar 2005 17:02:31 +0100, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>"Keith" wrote:
>
>> Is there a function for comparing version numbers?
>>
>> E.g.
>>
>> 0.1.0 < 0.1.2
>> 1.876b < 1.876c
>> 3.2.2 < 3.4
>
>the following works for many common cases:
>
>import re
>
>def cmpver(a, b):
>    def fixup(i):
>        try:
>            return int(i)
>        except ValueError:
>            return i
>    a = map(fixup, re.findall("\d+|\w+", a))
>    b = map(fixup, re.findall("\d+|\w+", b))
>    return cmp(a, b) # -1 if a<b, 0 if a=b, 1 if a>b

[OT] Visually, I like the nested def fixup, and I realize
that for cmpver execution overhead is not likely to be an issue,
but in general, what do you think of not being able
to write it that way if MAKE_FUNCTION overhead is unacceptable?

What if we had something like

@sticky('fixup') # evaluate binding only first time
def cmpver(a , b):
   def fixup ... ?

Regards,
Bengt Richter



More information about the Python-list mailing list