Low-hassle PEP-396

PEP-396 suggests that all python packages should provide a __version__ attribute. This should contain a string in the form x.y.z which gives you the package’s version number.

That seems simple enough, except that Python does not provide an obvious way to set this attribute. It would be a tremendous waste of time to set this manually before each script.

The obvious (and in my opinion wrong) way to fix this problem is to add something to the release process which automatically writes some text to the package’s __init__ file. Personally I don’t like self-modifying code. Python is dynamic enough already!

A much simpler way to do it is to exploit the pkg_resource module. In your package’s main __init__.py file, simply add the following lines:

import pkg_resources
__version__ = pkg_resources.working_set.by_key['<your package name>'].version

3 thoughts on “Low-hassle PEP-396

  1. As much as I am an advocate of PEP-396 conformance, it would be appropriate to mention its status is “Deferred”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s