|
| 1 | +.. _`Single sourcing the version`: |
| 2 | + |
| 3 | +=================================== |
| 4 | +Single-sourcing the Project Version |
| 5 | +=================================== |
| 6 | + |
| 7 | +:Page Status: Complete |
| 8 | +:Last Reviewed: 2015-09-08 |
| 9 | + |
| 10 | +One of the challenges in building packages is that the version string can be required in multiple places. |
| 11 | + |
| 12 | +* It needs to be specified when building the package (e.g. in pyproject.toml) |
| 13 | + - That will assure that it is properly assigned in the distribution file name, and in teh installed package. |
| 14 | + |
| 15 | +* Some projects require that there be a version string available as an attribute in the importable module, e.g:: |
| 16 | + |
| 17 | + import a_package |
| 18 | + print(a_package.__version__) |
| 19 | + |
| 20 | +While different projects have different needs, it's important to make sure that there is a single source of truth for the version number. |
| 21 | + |
| 22 | +In general, the options are: |
| 23 | + |
| 24 | +1) If the code is in a version control system (VCS), e.g. git, then the version can be extracted from the VCS. |
| 25 | + |
| 26 | +2) The version can be hard-coded into the `pyproject.toml` file -- and the build system can copy it into other locations it may be required. |
| 27 | + |
| 28 | +3) The version string can be hard-coded into the source code -- either in a special purpose file, such as `_version.txt`, or as a attribute in the `__init__.py`, and the build system can extract it at build time. |
| 29 | + |
| 30 | +If the version string is not in the source, it can be extracted at runtime with code in `__init__.py`, such as:: |
| 31 | + |
| 32 | + import importlib.metadata |
| 33 | + __version__ = importlib.metadata.version('the_distribution_name') |
| 34 | + |
| 35 | + |
| 36 | +Consult your build system documentation for how to implement your preferred method. |
| 37 | + |
| 38 | +Put links in to build system docs? |
| 39 | +-- I have no idea which are currently robust and maintained -- do we want to get into seeming endorsing particular tools in this doc? |
| 40 | + |
| 41 | + |
| 42 | +* setuptools: |
| 43 | + |
| 44 | +* hatch: |
| 45 | + |
| 46 | +* poetry: |
| 47 | + |
| 48 | +* PyBuilder: |
| 49 | + |
| 50 | +* Others? |
| 51 | + |
0 commit comments