0

I am looking for a way to specify my python program version (not the interpreter) exclusively in setup.cfg and use it at runtime in my python program - it appears to be the modern way to use only setup.cfg and omit setup.py altogether, as documented here: https://setuptools.pypa.io/en/latest/userguide/declarative_config.html

This topic seems quite involved with a lengthy discussion spanning years and no clear answer, as described here: Standard way to embed version into Python package?

What I'd like to achieve is that my setup.cfg has the version number (and all other relevant package data) and make that version available to my program at runtime.

Example setup.cfg

[metadata]
name = my_app
version = 0.1.3
author = foo
...

and then in my runtime access that version number:

2022-02-04T23:01:28.177 INFO root::============= Welcome to my_app version 0.1.3, PID: 52296 =============

How can I achieve that ?

1 Answer 1

2

Two options I can think of – I'd go with the first.

1. Use setup.cfg's attr: support to read the version from the source

setup.cfg

[metadata]
version = attr:my_app.__version__

my_app/init.py

# ...
__version__ = '0.1.3'

2. Use importlib.metadata to read the version from the installation metadata

(New in Python 3.8, has backports for older Pythons)

from importlib.metadata import version

my_version = version('my_app')  
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, always nice to have a simple solution. To me they both have their pros and cons - why do you prefer the first one ?
More version compatibility, no extra import on your app's behalf.
Ok thanks for the response. Tested both, both work. I respect your opinion and chose option 2 because it keeps the version number separate from the code itself - just a matter of preference for me, though.
You might want to consider splitting your answer into two answers. This way the community can vote on which one they prefer ;)
@Neuron Upvotes mean "This answer is useful". Both approaches here are useful, IMO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.