(1) One option is to get the version number in real-time from the release version written into a published package. To do this, you would add a dependency to __init__.py
, release the product with something like setup.py
and at runtime execute python3 setup.py --version
. This approach uses the lightweight importlib_metadata module [importlib_metadata
(for pre Python 3.8) and importlib.metadata
(for Python 3.8+)]:
from importlib.metadata import version, PackageNotFoundError
# pre-3.8 import statement
# from importlib_metadata import version, PackageNotFoundError
VERSION_FALLBACK = "0.0.0"
try:
__version__ = version(__name__)
except PackageNotFoundError:
# package is not installed
# assign signal or sane value as a default
__version__ = VERSION_FALLBACK
pass
This implements metadata recommendations from PEP 566. If you release with setuptools>=42.0.0
this works great, and it may work with packages released by other tooling, also.
(2) A second option is to do something with Git to collect the last tag value (assuming you are tagging the application). Then increment the point version number. Then replace the value in the init file with the new value and tag with the new value.
# get and increment semantic version
version=$( git tag --list | sort -rV | head -1 ); # v0.1.1
version_point=${version##*.} # 1
version_point=$((${version_point} + 1)) # 2
version="${version%.*}.${version_point}" # v0.1.2
# replace in __init__.py (NOTE: THIS OVERWRITES!)
cat __init.py__ | sed -e "s/VERSION=.*/VERSION=${version}/i" > __init__.py
git add __init__.py && git commit -m "Updated version in __init__.py"
git tag -a ${version} -m "Latest tagged version"