Search code examples
pythonsetuptools

display __version__ using setuptools.setup values in setup.py


I have a packaged project mytools which uses setuptools' setup to store its version in a setup.py project file e.g.

import setuptools

setuptools.setup(
name='mytools',
version='0.1.0'
)

I'd like to get the common mytools.__version__ feature based on the version value e.g.

import mytools
mytools.__version__
>>>'0.1.0'

Is there native / simple way in setuptools to do so? Couldn't find a reference to __version__ in setuptools. Furthermore, I don't want to store the version in __init__.py because I'd prefer to keep the version in its current place (setup.py). The many answers to similar questions do not speak to my specific problem, e.g. How can I get the version defined in setup.py (setuptools) in my package?


Solution

  • Adding __version__ to all top-level modules and packages is an outdated recommendation dating back from PEP 396 which was never actually accepted into a standard, and I do not recommend implementing this idea. Here are some messages raising concerns raised about this idea and its actual usefulness, for example here:

    With that said...

    Such a thing is often solved like the following:

    # my_top_level_module/__init__.py
    
    import importlib.metadata
    
    __version__ = importlib.metadata.version('MyProject')
    

    References: