2

When using setup.py in a Python project, we can simply run

$ python3 setup.py --version

And this will give us the version field that is set in the setup.py file. This saves us using sed or something alike to read the version when we need to do so in a script.

I was wondering, is there an equivalent way in a setup.cfg project?

sinoroc
  • 18,409
  • 2
  • 39
  • 70
YoavKlein
  • 2,005
  • 9
  • 38

2 Answers2

3

When you have only a setup.cfg, and no setup.py file, you can do this:

$ cat setup.cfg
[metadata]
name = mypkg
version = "0.1.2.3"  # or `file: VERSION.txt` or `attr: mypkg.__version__` etc

$ python3 -c 'import setuptools; setuptools.setup()' --version
"0.1.2.3"

If the build backend is setuptools, then this approach will also work for a source tree with a pyproject.toml file.

wim
  • 338,267
  • 99
  • 616
  • 750
-1

Allow me to deviate from your actual question to offer what I thing is a better solution.

If you have to get the package version while developing (from an outside script) then you should split such information from your setup.cfg/setup.py.

You want setup.cfg (i.e, setuptools) to get that information from a file, for instance. Then, you can have the version just by reading the corresponding file.

Check the docs for details: https://setuptools.pypa.io/en/latest/userguide/declarative_config.html. Notice the #meta-1 anchor/note in that page.

Basically, you'll use attr or file attributes (in your setup.cfg metadata section) to get the version from another place:

version = file: VERSION.txt
Brandt
  • 5,058
  • 3
  • 28
  • 46
  • This does not answer the question (_"to read the version when we need to do so in a script"_), and besides, the advice is outdated anyway. – wim Aug 10 '22 at 18:14
  • @wim how come is outdated? – Brandt Aug 10 '22 at 18:16
  • 1
    No matter whether version metadata is defined statically or dynamically, doing it in `pyproject.toml` is the modern way, not in random other files. See [PEP 621](https://peps.python.org/pep-0621/#version). – wim Aug 10 '22 at 18:19
  • @wim works pretty well for me. By all means, thanks for the update. – Brandt Aug 10 '22 at 18:24