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'>]
Prometheus
  • 32,405
  • 54
  • 166
  • 302

2 Answers2

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

val
  • 8,459
  • 30
  • 34
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.")
ferdy
  • 7,366
  • 3
  • 35
  • 46