This compares a few ways to give a Python project version metadata and a
top-level __version__ attribute, while specifying the version in only one
place, and where mypy and pyright can still do strict type checking.
This is not exhaustive. There are other techniques besides the ones shown here.
In addition, this only shows how to apply the techniques when configuring the
package in pyproject.toml and using setuptools as a build backend.
-
by_literal/- Set the value of__version__in the package's top-level__init__.py, and have the build backend parse it out. -
by_getattr/- Define__getattr__in the package's top-level__init__.pythat dynamically retrieves version metadata on demand when__version__is accessed. (This requires some extra work to get precise type hinting, sincemypyrejectsLiteral["__version__"]as a parameter type annotation for module-level__getattr__.) -
by_property/- Create a subclass ofModuleTypewith a__version__property that dynamically retrieves version metadata on demand. Rebind the package's__class__attribute to that new class.
Checks can be run together with tox.
To do so, install tox if it is not already installed. Make sure you have
version 4 or higher.
Then, at the top of this repository's working tree (the directory that contains
tox.ini), test and typecheck any of the individual packages as follows:
tox --root by_literal
tox --root by_getattr
tox --root by_property