Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify version parsing example #571

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 12 additions & 20 deletions source/guides/single-sourcing-package-version.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,26 @@ Single-sourcing the package version
There are many techniques to maintain a single source of truth for the version
number of your project:

#. Read the file in :file:`setup.py` and parse the version with a regex.
Example ( from `pip setup.py
<https://github.com/pypa/pip/blob/master/setup.py#L12>`_)::
#. Read the file with version info in :file:`setup.py` and parse version line.
Example::

here = os.path.abspath(os.path.dirname(__file__))
import os

def read(*parts):
with codecs.open(os.path.join(here, *parts), 'r') as fp:
return fp.read()

def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
def get_version(rel_path):
current_dir = os.path.abspath(os.path.dirname(__file__))
version_file = os.path.join(current_dir, rel_path)
for line in open(version_file, 'rb'):
if line.startswith(b'__version__'):
# __version__ = "0.9"
delim = b'\"' if b'\"' in line else b'\''
return line.split(delim)[1].decode()

setup(
...
version=find_version("package", "__init__.py")
version=get_version("package/__init__.py"),
...
)

.. note::

This technique has the disadvantage of having to deal with complexities of regular expressions.

#. Use an external build tool that either manages updating both locations, or
offers an API that both locations can use.

Expand Down