6

In order to simplify python packaging I am trying to migrate to use of pbr.

Still, I was not able to figure out how to expose the version of the package into __version__ variable.

This is quite important because I do have many users of the package that do rely on the existence of the version variable.

People should be able to do:

import somemodule
print(somemodule.__version__)
sorin
  • 161,544
  • 178
  • 535
  • 806

2 Answers2

3

I am not sure if that's the best approach but I was able to spot one other packages that is doing something similar: mock.

__all__ = (
    '__version__',
    'version_info'
)

from pbr.version import VersionInfo

_v = VersionInfo('mock').semantic_version()
__version__ = _v.release_string()
version_info = _v.version_tuple()
sorin
  • 161,544
  • 178
  • 535
  • 806
  • I find it curious/frustrating that pbr doesn't need a dependency when in `setup.py` but when I try and use it in my command line script I have to list it in `requirements.txt` – Lucas Aug 30 '17 at 20:30
  • @Lucas that is not really true that "pbr does not need dependency in setup.py" it actually is specified as setup dependency: `setup_requires=['pbr']` But agree that this is not really clean solution... – AuHau Nov 17 '18 at 00:30
3

As the existing answer wasn't clear on some of the setup required, here is a reply with some more context.

Update your version string

First, update your version string in your setup.cfg, if tracking it manually there.

Otherwise, if pulling version and other info from the git repo:

  • make your new commit
  • generate a new version tag (if not a development release)
  • run py setup.py sdist to generate your distribution and update local files based on the git info (AUTHORS, ChangeLog, etc.).

Note: The quickest command to generate new version from updated Git tags is python setup.py install, but I've seen a warning not to use that. It's working fine for me, but may just be my particular setup. Using the sdist or a bdist_xxx will generate a full distribution that you need to delete if you aren't using it.

Setup package __init__.py

my_package/init.py

all = ('__version__',)

from pbr.version import VersionInfo

# Check the PBR version module docs for other options than release_string()
__version__ = VersionInfo('<my_package>').release_string()

Then in the script using the package

my_script.py

import my_package

print(my_package.__version__)

For more details, see the pbr.version module documentation.

LightCC
  • 9,804
  • 5
  • 52
  • 92
  • Shouldn't the first line in `__init__.py` be `__all__ = ('__version__',)`? Note the trailing comma to make the value a tuple, not a string. – akaihola Feb 18 '20 at 07:53
  • 1
    @akaihola Yes, that looks right. Updated, but not tested - I've moved on to using the Poetry package with poetry-dynamic-versioning to manage version in Python repos. – LightCC Dec 27 '22 at 18:06