We have a big legacy project that contains some python code inside, the version of all components in the project is set during runtime by the build system which builds the project. We now need to package the python code with the same version used by the other components.
The package is currently archived using the following command python setup.py bdist_wheel with no versioning.
The question is how can we pass the dynamic version to the setup.py command during build time. Something like:
python setup.py --version x.x.x bdist_wheel
There are several options to override a version file like version.py or version.txt with the new version and then use it in the setup.py file, but assuming we can't add any more steps to the build process and can only modify the build command and the python files how can it be done?
Additional requirements:
- In case no version is passed a default value should be used.
- The version should be available in the python code (like having it as a
__version__parameter in the__init__.py) - If possible should support the usage of
setup.cfgorpyproject.tomlfor metadata configuration
If you choose to only use
setup.pyand excludepyproject.tomlandsetup.cfg, you can retrieve the version of your package using Python code in any way that you prefer. For instance, you can obtain the version by reading an environment variable (e.g.EXAMPLE_VERSION) within thesetup.pyscript:Code is from this gist.
Run
to build the dist
package_name-0.1.0-py3-none-any.whlHowever, if you want the version to be available in the variable
__version__in the__init__.pyfile of your module, you need to dynamically update the value of this variable when running thesetup.pyscript. Here is an example:Running
will build the bdist_wheel with the version 0.2.0. Before that, the
__version__variable in the__init__.pyis updated. After executing thesetuptools.setupcommand, the content of the__init__.pyis restored. Please note that I'm assuming a src layout here.I haven't played around with the
pyproject.tomlorsetup.cfgconfig files, but restricting yourself to only using thesetup.pyallows you to write code that does what you want.