如何通过pbr从Git标签获取版本并在包内实现__version__属性
Absolutely! You can absolutely use pbr to expose the Git-tag-derived version as a __version__ attribute in your package—no need for versioneer or extra runtime dependencies. Here's how to set it up step by step:
Step 1: Configure your setup.py for pbr
First, make sure your setup.py is set up to leverage pbr. You don’t need to hardcode a version here; pbr will handle pulling it directly from your Git tags automatically. Your setup.py can be as minimal as:
from setuptools import setup setup( setup_requires=['pbr'], pbr=True, )
You can optionally add a setup.cfg file to customize pbr’s behavior (like adjusting version format rules), but the default settings work perfectly for most cases—pbr will even automatically strip the v prefix from tags like v1.0.0 to get a clean version string.
Step 2: Add version import to your package's init.py
When you run any setup command (like install, sdist, or develop), pbr automatically generates a _version.py file in your package directory. This file contains both a version_info tuple and a pre-formatted __version__ string. To expose this to users of your package, add this snippet to your package’s __init__.py:
try: from ._version import version_info, __version__ except ImportError: # Fallback for fresh clones where _version.py hasn't been generated yet version_info = (0, 0, 0, 'dev', 0) __version__ = '.'.join(map(str, version_info[:3])) + ''.join(version_info[3:])
This fallback ensures your package still works if someone clones the repo and imports it directly without running a setup command first.
Step 3: Verify it works
- Run
python setup.py develop(for a development environment) orpip install .(to install the package normally). - Open a Python shell, import your package, and check the version:
You’ll see the version pulled from your latest Git tag, plus aimport mypackage print(mypackage.__version__).devXXXsuffix if there are uncommitted changes or new commits after the tag—this is pbr’s default behavior for tracking development state.
Why this beats versioneer for your use case
Unlike versioneer, pbr doesn’t require adding extra files to your repo or including it as a runtime dependency. The _version.py file is generated at build/install time, so your final package has zero reliance on pbr—only the setup process uses it.
内容的提问来源于stack exchange,提问作者Roy Prins

