Skip to content
53 changes: 26 additions & 27 deletions source/single_source_version.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,20 @@ number of your project:
#. Read the file in ``setup.py`` and parse the version with a regex. Example (
from `pip setup.py <https://github.com/pypa/pip/blob/1.5.6/setup.py#L33>`_)::

def read(*names, **kwargs):
with io.open(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf8")
) as fp:
return fp.read()
import os.path
import re

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)
# We read __version__ instead of importing it because that would fail if
# the module it's in tries to import things from dependencies that aren't
# installed yet when setup.py is being run.
# Moreover, imports can fail if sys.path isn't properly set.
# Since version numbers only use a subset of ascii, we can read the file
# as bytes, thus avoiding unicode decode errors.
with open(os.path.join(os.path.dirname(__file__), *file_paths), 'rb') as f:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add some explanation of the use of 'rb' and 'br' to convince readers (and me) that this will always work.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see this change as an advantage. It's technically correct, I guess, but the files in question are actually text files, and reading them as such seems more logical (even if it does mean you need to think about encodings).

Binary reading a text file just to avoid thinking about encodings feels like a hack (and the sort of thinking that the string changes in Python 3 were explicitly designed to discourage).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What we're trying to extract, i.e. the version number, only uses a subset of ascii characters, so we don't need to deal with unicode. 'rb' tells python to read the file as bytes without trying to decode them, and since we're reading bytes we need the regexp pattern to be bytes (otherwise python 3 will raise TypeError: cannot use a string pattern on a bytes-like object), thus 'br'.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this be satisfactory?

# Since version numbers only use a subset of ascii, we can read the file
# as bytes, thus avoiding unicode decode errors.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment added.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: I did search the stdlib for a function that properly decodes a python file (i.e. by looking for the # coding: header), but I couldn't find one, so reading the file as bytes is easier.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These exist in Python 3 (as tokenize.open() and tokenize.detect_encoding()), but for 2/3 compatible code, assuming ASCII compatibility and reading the bytes is the most straightforward option. We assume ASCII compatibility in other aspects of the packaging ecosystem (most notably distribution package names), so it's a reasonable assumption to make here as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @ncoghlan :-)

match = re.search(br"^__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M)
if match:
return match.group(1)
raise RuntimeError("Unable to find version string.")

setup(
Expand All @@ -48,25 +49,23 @@ number of your project:


#. Set the value to a ``__version__`` global variable in a dedicated module in
your project (e.g. ``version.py``), then have ``setup.py`` read and ``exec`` the
value into a variable.
your project (e.g. ``__about__.py``), then have ``setup.py`` read and ``exec`` the
value into a variable::

Using ``execfile``:
import os.path

::

execfile('...sample/version.py')
# now we have a `__version__` variable
# later on we use: __version__

Using ``exec``:

::
# We exec the module instead of importing it because imports can fail if
# sys.path isn't properly set.
base_dir = os.path.dirname(__file__)
about = {}
with open(os.path.join(base_dir, "module_name", "__about__.py"), 'rb') as fp:
exec(fp.read(), {}, about)

version = {}
with open("...sample/version.py") as fp:
exec(fp.read(), version)
# later on we use: version['__version__']
setup(
...
version=about['__version__']
...
)

Example using this technique: `warehouse <https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py>`_.

Expand Down