DEV Community

Sean Francis N. Ballais
Sean Francis N. Ballais

Posted on

I am kind of baffled by this code in the `__init__.py` file in my Python project. How does this work internally?

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'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Top comments (8)

Collapse
 
rhymes profile image
rhymes

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.

Collapse
 
seanballais profile image
Sean Francis N. Ballais

In what cases would you need to find the package version at runtime?

Collapse
 
rhymes profile image
rhymes

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 :(

Thread Thread
 
seanballais profile image
Sean Francis N. Ballais

It's alright.

Collapse
 
samuelabreu profile image
Samuel Abreu

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.

Collapse
 
seanballais profile image
Sean Francis N. Ballais

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?

Collapse
 
grahamlyons profile image
Graham Lyons

It would suffice. This would just avoid the duplication by only having it set in setup.py and reading the value from there.

Collapse
 
daveshawley profile image
dave-shawley

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.