A build-system independent way to get the version from a package source directory

197 views Asked by At

There are many different ways that Python packages manage their version data. Is there a build-system independent way to extract the version from a package source directory?

I'm aware of the PEP 517 compatible Python package builder build which does this internally. For instance, in an example source directory for a Python package my_pkg:

$ python -m build --sdist
...
Successfully built my_pkg-1.2.0.tar.gz

so is there a clever way to just extract the version number without building the distribution?

1

There are 1 answers

0
wim On BEST ANSWER

No. The only mandatory hooks currently specified for a PEP 517 build backend are the build hooks:

def build_sdist(sdist_directory, config_settings=None):
    ...

def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
    ...

The build process also generates the package metadata, including the Version field. In the general case, it is necessary to execute a build to get the version info.

Note that it's also fairly common for the version info to be generated dynamically, e.g. sourcing it from the underlying version control system, so discovering the version from the source directory without a build would only be possible in a subset of cases anyway.

Some build backends may provide other ways to get the version, for example in setuptools you could use:

python3 -c 'import setuptools; setuptools.setup()' --version

However, PEP 517 has nothing to say about this, and it will be specific to the build backend.

For a backend-agnostic way to generate the version, you could use build.util.project_wheel_metadata, but this may actually execute a build.