Checking a Python module version at runtime Checking a Python module version at runtime python python

Checking a Python module version at runtime


Use pkg_resources. Anything installed from PyPI at least should have a version number.

>>> import pkg_resources>>> pkg_resources.get_distribution("blogofile").version'0.7.1'


I'd stay away from hashing. The version of libxslt being used might contain some type of patch that doesn't effect your use of it.

As an alternative, I'd like to suggest that you don't check at run time (don't know if that's a hard requirement or not). For the python stuff I write that has external dependencies (3rd party libraries), I write a script that users can run to check their python install to see if the appropriate versions of modules are installed.

For the modules that don't have a defined 'version' attribute, you can inspect the interfaces it contains (classes and methods) and see if they match the interface they expect. Then in the actual code that you're working on, assume that the 3rd party modules have the interface you expect.


If you're on python >=3.8 you can use a module from the built-in library for that. To check a package's version (in this example lxml) run:

>>> from importlib.metadata import version>>> version('lxml')'4.3.1'

This functionality has been ported to older versions of python (<3.8) as well, but you need to install a separate library first:

pip install importlib_metadata

and then to check a package's version (in this example lxml) run:

>>> from importlib_metadata import version>>> version('lxml')'4.3.1'

Keep in mind that this works only for packages installed from PyPI. Also, you must pass a package name as an argument to the version method, rather than a module name that this package provides (although they're usually the same).