How to raise an exception to the module version number

How can you throw an exception when importing a module that is less than or greater than the given value for its __version __?

There are many different ways to do this, but I feel that there must be some really easy way that is eluding me at the moment. In this case, the version number is in xxx format

+4
source share
5 answers

Python comes with this built-in 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 more information than you need, see the documentation:

 >>> import distutils.version >>> help(distutils.version) 
+6
source

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 cause an error if the installed module has 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')) 
+2
source

Like this?

 assert tuple(map(int,module.__version__.split("."))) >= (1,2), "Module not version 1.2.x" 

This is verbose, but works very well.

Also check out pip , which provides more advanced features.

+1
source

You should use setuptools:

It allows you to block the dependence of the application, therefore, even if there are several versions of the egg or package in the system, only the correct one will be used.

This is the best way to work: instead of failing if the wrong version of the dependencies is present, it is better to make sure the correct version is available.

Setuptools provides an installer that ensures that everything you need to run the application is present during installation. It also gives you the opportunity to choose which of the many versions of the package that may be present on your PC is the one that loads when the import statement is issued.

0
source

If you know the exact formatting of the version string, a simple comparison will be performed:

 >>> "1.2.2" > "1.2.1" True 

This will only work if each part of the version is in one digit:

 >>> "1.2.2" > "1.2.10" # Bug! True 
-1
source

All Articles