How can I get the version defined in setup.py (setuptools) in my package?

elmarco picture elmarco · Jan 13, 2010 · Viewed 82.9k times · Source

How could I get the version defined in setup.py from my package (for --version, or other purposes)?

Answer

PJ Eby picture PJ Eby · Jan 15, 2010

Interrogate version string of already-installed distribution

To retrieve the version from inside your package at runtime (what your question appears to actually be asking), you can use:

import pkg_resources  # part of setuptools
version = pkg_resources.require("MyProject")[0].version

Store version string for use during install

If you want to go the other way 'round (which appears to be what other answer authors here appear to have thought you were asking), put the version string in a separate file and read that file's contents in setup.py.

You could make a version.py in your package with a __version__ line, then read it from setup.py using execfile('mypackage/version.py'), so that it sets __version__ in the setup.py namespace.

If you want a much simpler way that will work with all Python versions and even non-Python languages that may need access to the version string:

Store the version string as the sole contents of a plain text file, named e.g. VERSION, and read that file during setup.py.

version_file = open(os.path.join(mypackage_root_dir, 'VERSION'))
version = version_file.read().strip()

The same VERSION file will then work exactly as well in any other program, even non-Python ones, and you only need to change the version string in one place for all programs.

Warning about race condition during install

By the way, DO NOT import your package from your setup.py as suggested in another answer here: it will seem to work for you (because you already have your package's dependencies installed), but it will wreak havoc upon new users of your package, as they will not be able to install your package without manually installing the dependencies first.