Skip to main content

Extract your project's __version__ variable

Project description

Project Status: Active — The project has reached a stable, usable state and is being actively developed. MIT License!-1EAEDB.svg

GitHub | PyPI | Issues | Changelog

When creating a for a new project, do you find yourself always writing the same block of code for parsing __version__ from your project’s source? Something like this?

with open(join(dirname(__file__), 'package_name', '')) as fp:
    for line in fp:
        m ='^\s*__version__\s*=\s*([\'"])([^\'"]+)\1\s*$', line)
        if m:
            version =
        raise RuntimeError('Unable to find own __version__ string')

    version = version,

Someone needs to put all that into a reusable package, am I right? Well, someone did, and this is that package. It exports a single function that does the above, perfect for importing into your, and (New in v0.2.0!) this package even lets you map Python variables to supported metadata fields via your pyproject.toml.


Just use pip (You have pip, right?) to install read_version:

pip install read_version

read_version also has a toml extra that provides support for reading configuration from pyproject.toml. Install it with:

pip install 'read_version[toml]'


The Functional Way

  1. Install read_version in your development environment.

  2. Add a pyproject.toml file to your project declaring read_version as a build dependency. (This is needed so that other people can build your package from source; see PEP 518 for more information.) The contents of the file should look like:

    requires = [
        "read_version ~= 0.3.0",
    build-backend = "setuptools.build_meta"
  3. In your, get rid of your boilerplate __version__-finding code and replace it with:

    from read_version import read_version
        version = read_version('packagename', ''),
  4. Build your project and double-check that the version is set to the correct value.

  5. Done!

The Declarative Way

New in version 0.2.0!

  1. Install read_version in your development environment with the toml extra:

    pip install 'read_version[toml]'

    You will also need version 42.0.0 or later of setuptools:

    pip install -U 'setuptools>=42'
  2. Add a pyproject.toml file to your project declaring read_version[toml] as a build dependency and also requiring version 42.0.0 or later of setuptools. The relevant section of the file should look like:

    requires = [
        "read_version[toml] ~= 0.3.0",
        "setuptools >= 42.0.0",
    build-backend = "setuptools.build_meta"
  3. Get rid of your boilerplate __version__-finding code in your Instead, add a tool.read_version table to your pyproject.toml file, and for each metadata field that you want to be read from a variable in a Python source file, add an entry to this table of the form FIELD = "dotted.file.path:varname", where:

    • FIELD is replaced by the lowercase name of the field. Supported fields are:

      • author
      • author_email
      • description (Note that this is the short description or summary, not the long description!)
      • keywords (It is recommended to use a list of strings as the value or else setuptools might mangle it)
      • license
      • maintainer
      • maintainer_email
      • url
      • version

      Entries with unsupported or unknown field names are ignored.

    • dotted.file.path is replaced by the path (relative to the project root) to the file containing the variable, with path components separated by dots and the .py at the end of the last path component dropped

    • varname is replaced by the name of the variable to read


    # Set the project's version to the value of __version__ in
    version = "foobar:__version__"
    # Set the project's author to the value of author_name in
    # foobar/
    author = "foobar.__init__:author_name"
    # Set the project's license to the value of LICENSE in
    # src/foobar/
    license = "src.foobar.about:LICENSE"

    If this syntax doesn’t work for you — say, because one of your path components contains a period or colon in its name, or because the file doesn’t have a .py extension — or if you want to set a default value for when the variable isn’t found, then make tool.read_version.FIELD into a table, like so:

    # Set the project's version to the value of __version__ in
    path = ["", "__init__.pyq"]
    variable = "__version__"
    # Set the project's author_email to the value of EMAIL in
    # If the variable isn't found, use the value "" instead
    # of erroring
    path = [""]
    variable = "EMAIL"
    default = ""

    tool.read_version.FIELD tables may contain the following keys:

    path:(Required) The path to the source file containing the variable to read, relative to the project root, as a list of path components
    variable:(Required) The name of the Python variable to get the value from
    default:(Optional) If the variable cannot be found in the source file, use the given value instead; if the variable cannot be found and default is not set, an error will occur
  4. Build your project and double-check that the metadata has all the relevant fields set to their correct values.

  5. Done!


read_version exports a single function, also named read_version, whose signature is:

read_version(*filepath, variable='__version__', default=NOTHING)

read_version() takes one or more file path components pointing to a Python source file to parse. The path components will be joined together with os.path.join(), and then, if the path isn’t absolute, the path to the directory containing the script calling read_version() will be prepended to the path. (No more join(dirname(__file__), ...) boilerplate needed!) read_version() then parses the given Python file and searches through the parse tree for any assignments to a variable named __version__, returning the last value assigned.

The variable keyword argument can be set to the name of a variable other than __version__ to search for assignments to a different variable instead. Setting it to "__doc__" causes the function to return the module docstring.

If no assignments to the variable are found, a ValueError is raised. To instead return a default value when this happens, set the default keyword argument.


read_variable only finds assignments that occur at the top level of the module, outside of any blocks.

Only assignments of literal values are supported; assignments to the searched-for variable involving more complicated expressions will cause an error to be raised.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for read-version, version 0.3.1
Filename, size File type Python version Upload date Hashes
Filename, size read_version-0.3.1-py2.py3-none-any.whl (8.5 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size read_version-0.3.1.tar.gz (15.6 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page