Search code examples
pythonpython-packagingpython-poetry

Get version of Python poetry project from inside the project


I have a python library packaged using poetry. I have the following requirements

Inside the poetry project

# example_library.py
def get_version() -> str:
    # return the project version dynamically. Only used within the library

def get_some_dict() -> dict:
    # meant to be exported and used by others
    return {
        "version": get_version(),
        "data": #... some data
    }

In the host project, I want the following test case to pass no matter which version of example_library I'm using

from example_library import get_some_dict
import importlib.metadata
version = importlib.metadata.version('example_library')

assert get_some_dict()["version"] == version 

I have researched ideas about reading the pyproject.toml file but I'm not sure how to make the function read the toml file regardless of the library's location.

The Poetry API doesn't really help either, because I just want to read the top level TOML file from within the library and get the version number, not create one from scratch.


Solution

  • Use importlib.metadata.version() from Python's own standard library:

    import importlib.metadata
    
    version = importlib.metadata.version('ProjectName')
    

    This is not specific to Poetry and will work for any project (library or application) whose metadata is readable.

    Make sure that ProjectName is installed. Where ProjectName can be your own library or a 3rd party library, it does not matter. And note that a so-called "editable" installation is also good enough.

    Documentation for importlib.metadata.version().

    See also: