pythonsetuptoolssetup.pypython-packaging

Standard way to embed version into Python package?


Is there a standard way to associate version string with a Python package in such way that I could do the following?

import foo
print(foo.version)

I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in setup.py already. Alternative solution that I found was to have import __version__ in my foo/__init__.py and then have __version__.py generated by setup.py.


Solution

  • Not directly an answer to your question, but you should consider naming it __version__, not version.

    This is almost a quasi-standard. Many modules in the standard library use __version__, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.

    Usually, __version__ is a string, but sometimes it's also a float or tuple.

    As mentioned by S.Lott (Thank you!), PEP 8 says it explicitly:

    Module Level Dunder Names

    Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__, __author__, __version__, etc. should be placed after the module docstring but before any import statements except from __future__ imports.

    You should also make sure that the version number conforms to the format described in PEP 440 (PEP 386 a previous version of this standard).