pythonsetuptools

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


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


Solution

  • 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.

    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.