How to raise an exception on the version number of a module

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

Asked by: Andrew868 | Posted: 06-10-2021

Answer 1

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)

Answered by: Blake274 | Posted: 07-11-2021

Answer 2

If you are talking about modules installed with easy_install, this is what you need

import pkg_resources

this will raise an error if the installed module is of a lower version

Traceback (most recent call last):
  File "", line 2, in <module>
  File "/usr/lib/python2.5/site-packages/", line 626, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/usr/lib/python2.5/site-packages/", line 528, in resolve
    raise VersionConflict(dist,req) # XXX put more info here
pkg_resources.VersionConflict: (TurboGears (/usr/lib/python2.5/site-packages/TurboGears-, Requirement.parse('TurboGears>=1.0.5'))

Answered by: Alina612 | Posted: 07-11-2021

Answer 3

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.

Answered by: Arnold154 | Posted: 07-11-2021

Answer 4

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.

Answered by: Clark822 | Posted: 07-11-2021

Answer 5

If you know the exact formatting of the version string a plain comparison will work:

>>> "1.2.2" > "1.2.1"

This will only work if each part of the version is in the single digits, though:

>>> "1.2.2" > "1.2.10" # Bug!

Answered by: Roman211 | Posted: 07-11-2021

Similar questions

exception - Checking for member existence in Python

I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like this: class Foo(object): @classmethod def singleton(self): if not hasattr(self, 'instance'): self.instance = Foo() return self.instance But you can also do this: class...

Python: How to ignore an exception and proceed?

This question already has answers here:

How do I stop a program when an exception is raised in Python?

I need to stop my program when an exception is raised in Python. How do I implement this?

exception - Getting out of a function in Python

I want to get out of a function when an exception occurs or so. I want to use other method than 'return'

Exception handling of a function in Python

Suppose I have a function definiton: def test(): print 'hi' I get a TypeError whenever I gives an argument. Now, I want to put the def statement in try. How do I do this?

python - return eats exception

I found the following behavior at least weird: def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere? But the real ...

exception - Generic catch for python

I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of: try: # something that fails except e: print e A bit more about the problem at hand in detail: I have a Django app that on my computer (Ubuntu Linux 8.10) works fine both through runserver and mod-...

python - How to catch str exception?

import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad. except str,e: doesn't catch it? why? system: Python 2.5.2 (r252:60911, Ju...

unit testing - Python - test that succeeds when exception is not raised

I know about unittest Python module. I know about assertRaises() method of TestCase class. I would like to write a test that succeeds when an exception is not raised. Any hints please?

Catching an exception while using a Python 'with' statement

I can't figure out how to handle exception for python 'with' statement. If I have a code: with open(&quot;a.txt&quot;) as f: print f.readlines() I really want to handle 'file not found exception' in order to do somehing. But I can't write with open(&quot;a.txt&quot;) as f: print f.readlines() except: print 'oops' and can't write with...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python