0

Workout if a string holding a version number is higher than another string holding a version number in Python 3.

This is what I have tried:

request_version = "1.10.1"
current_version = "1.11"
if Decimal(request_version) > Decimal(current_version):
    pass

However, I get this error, why?

InvalidOperation at /api/version/
[<class 'decimal.ConversionSyntax'>]
9
  • Youe example works for me Commented Mar 7, 2016 at 11:45
  • 1
    its actually working for me... Commented Mar 7, 2016 at 11:45
  • 2
    Nope, works fine: repl.it/BteN. Are you sure you're not trying to take a patch release (e.g. 1.2.3) or something? Also, note that releases don't compare numerically - 1.2 is less recent than 1.11, even though it's a larger number, for example. Commented Mar 7, 2016 at 11:45
  • 2
    Well then: 1. The answer is obvious ("why?" - because 1.10.1 isn't a valid number); and: 2. You're still going to hit the problem that comparing them as numbers is precisely the wrong way to do this. Commented Mar 7, 2016 at 11:47
  • 2
    Version strings are not decimal numbers! Use functions specialised in comparing version strings. Commented Mar 7, 2016 at 11:47

2 Answers 2

4

You're trying to convert your version string to a float, which fails because 1.2.3 is not a valid float.

What you probably want for this kind of things is the packaging package, which implements the PEP 440 version semantics (among other niceties):

>>> from packaging.version import parse
>>> request_version = parse("1.10.1")
>>> current_version = parse("1.11")
>>> request_version > current_version
False
>>> request_version < current_version
True

This parse will create a Version object, which allows comparison between versions

Sign up to request clarification or add additional context in comments.

Comments

1

You might want to use LooseVersion from distutils.version:

from distutils.version import LooseVersion as V

current = V('1.10.1')
request_version = V('1.11')

if current < request_version:
    print("Yay.")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.