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 ?

Blindfreddy
  • 622
  • 6
  • 12

1 Answers1

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')  
AKX
  • 152,115
  • 15
  • 115
  • 172
  • 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 ? – Blindfreddy Feb 07 '22 at 16:10
  • More version compatibility, no extra import on your app's behalf. – AKX Feb 07 '22 at 17:17
  • 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. – Blindfreddy Feb 07 '22 at 22:55
  • You might want to consider splitting your answer into two answers. This way the community can vote on which one they prefer ;) – Neuron Jul 07 '22 at 10:24
  • @Neuron Upvotes mean "This answer is useful". Both approaches here are useful, IMO. – AKX Jul 07 '22 at 10:31