Reputation: 48416
How can you raise an exception when you import a module that is less or greater than a given value for its __version__?
There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x
Upvotes: 5
Views: 996
Reputation: 432
You can use packaging
https://packaging.pypa.io/en/stable/
from packaging import version
import pandas as pd
# Pandas 2.0 is required
assert version.parse(pd.__version__) >= version.parse("2.0.0")
Upvotes: 0
Reputation: 23018
You should be using setuptools:
It allows you to lock the dependancies of an application, so even if multiple versions of an egg or package exist on a system only the right one will ever be used.
This is a better way of working: Rather than fail if the wrong version of a dependancy is present it is better to ensure that the right version is present.
Setuptools provides an installer which guarantees that everything required to run the application is present at install-time. It also gives you the means to select which of the many versions of a package which may be present on your PC is the one that gets loaded when you issue an import statement.
Upvotes: 0
Reputation: 2698
If you are talking about modules installed with easy_install, this is what you need
import pkg_resources
pkg_resources.require("TurboGears>=1.0.5")
this will raise an error if the installed module is of a lower version
Traceback (most recent call last):
File "tempplg.py", line 2, in <module>
pkg_resources.require("TurboGears>=1.0.5")
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 626, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 528, in resolve
raise VersionConflict(dist,req) # XXX put more info here
pkg_resources.VersionConflict: (TurboGears 1.0.4.4 (/usr/lib/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg), Requirement.parse('TurboGears>=1.0.5'))
Upvotes: 2
Reputation: 3093
If you know the exact formatting of the version string a plain comparison will work:
>>> "1.2.2" > "1.2.1"
True
This will only work if each part of the version is in the single digits, though:
>>> "1.2.2" > "1.2.10" # Bug!
True
Upvotes: -3
Reputation: 32763
Python comes with this inbuilt as part of distutils. The module is called distutils.version
and is able to compare several different version number formats.
from distutils.version import StrictVersion
print StrictVersion('1.2.2') > StrictVersion('1.2.1')
For way more information than you need, see the documentation:
>>> import distutils.version
>>> help(distutils.version)
Upvotes: 6