So, I have the following Python code residing in the __init__.py
file of my Python project which I autogenerated using PyScaffold.
from pkg_resources import get_distribution, DistributionNotFound
try:
# Change here if project is renamed and does not equal the package name
dist_name = 'mlfq-sim'
__version__ = get_distribution(dist_name).version
except DistributionNotFound: # pragma: no cover
# Can't unit test this for now since I do not know how to temporarily
# remove a distribution during runtime. Help. Also, is this even
# worth it?
__version__ = 'unknown'
I get that it gets the version of my project. But how does it do it? Is there a benefit in using it compared to the one below?
__version__ = 'some version'
Top comments (8)
I didn't know about pyscaffold. get_distribution comes from setuptools which is a library to distribute Python projects.
That part I believe is about finding the package version at runtime.
I'd say unless you're shipping a library it's probably overkill.
In what cases would you need to find the package version at runtime?
Probably for conflict resolution in case multiple packages require your library with different versions...
I'm sorry Sean, I don't know much about this topic :(
It's alright.
Check the 5th item on packaging.python.org/guides/single...
It gets the version from setup.py, i believe it checks for dependencies on runtime.
I get the fact that it checks for dependencies (and their versions) on runtime. But I don't get why it would need to use
get_distribution()
to get the version of itself. Wouldn't__version__ = 'some_version'
suffice?It would suffice. This would just avoid the duplication by only having it set in
setup.py
and reading the value from there.Technically it gets the version from the named distribution’s metadata - usually the version kwarg to setuptools.setup() in setup.py. This can be different if setup.py dynamically appends SCM information to the hard-coded version number. Take a look at github.com/dave-shawley/setupext-g... for an example.