views:

131

answers:

5

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

+1  A: 

Like this?

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

This is wordy, but works pretty well.

Also, look into pip, which provides more advanced functionality.

S.Lott
+6  A: 

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)
Gerald Kaszuba
A: 

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
Algorias
+1  A: 

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'))
JV
A: 

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.

Salim Fadhley