Skip to content

Commit 89f8968

Browse files
authored
Merge pull request pypa#699 from lucatrv/update-version-sourcing-example
Update version sourcing example from pip setup.py
2 parents 06902b5 + f3d4c2b commit 89f8968

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

source/guides/single-sourcing-package-version.rst

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,31 @@ Single-sourcing the package version
88
There are many techniques to maintain a single source of truth for the version
99
number of your project:
1010

11-
#. Read the file in :file:`setup.py` and parse the version with a regex.
12-
Example ( from `pip setup.py
13-
<https://github.com/pypa/pip/blob/master/setup.py#L12>`_)::
11+
#. Read the file in :file:`setup.py` and get the version. Example (from `pip setup.py
12+
<https://github.com/pypa/pip/blob/master/setup.py#L11>`_)::
1413

15-
here = os.path.abspath(os.path.dirname(__file__))
14+
import codecs
15+
import os.path
1616

17-
def read(*parts):
18-
with codecs.open(os.path.join(here, *parts), 'r') as fp:
17+
def read(rel_path):
18+
here = os.path.abspath(os.path.dirname(__file__))
19+
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
1920
return fp.read()
2021

21-
def find_version(*file_paths):
22-
version_file = read(*file_paths)
23-
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
24-
version_file, re.M)
25-
if version_match:
26-
return version_match.group(1)
27-
raise RuntimeError("Unable to find version string.")
22+
def get_version(rel_path):
23+
for line in read(rel_path).splitlines():
24+
if line.startswith('__version__'):
25+
delim = '"' if '"' in line else "'"
26+
return line.split(delim)[1]
27+
else:
28+
raise RuntimeError("Unable to find version string.")
2829

2930
setup(
3031
...
31-
version=find_version("package", "__init__.py")
32+
version=get_version("package/__init__.py")
3233
...
3334
)
3435

35-
.. note::
36-
37-
This technique has the disadvantage of having to deal with complexities of regular expressions.
3836

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

0 commit comments

Comments
 (0)