1

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.

Beast
  • 370
  • 2
  • 14
  • Question asked many times. Use `import importlib.metadata; version = importlib.metadata.version('ProjectName')`. This is not specific to Poetry. Make sure that `ProjectName` is installed (editable installation is also good enough of course). [Documentation](https://docs.python.org/3/library/importlib.metadata.html#distribution-versions). – sinoroc Dec 14 '22 at 10:07
  • Seems like your code is meant to run in the project that imports the library. What I meant was: let's say we have a package called `file_processing`. Within `file_processing`, I have a function `file_processing.get_file_processing_version()`. I want its return value to be dynamic and I want to call this function within the library so this is independent of any host project. – Beast Dec 14 '22 at 13:12
  • What's the difference? This will also work to get the version of itself. -- Or I misunderstood your point. – sinoroc Dec 14 '22 at 13:28
  • Sorry. I have tried your suggestion and it works. Post it as an answer and I'll accept it or I can just delete this question – Beast Dec 15 '22 at 02:25

1 Answers1

0

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:

sinoroc
  • 18,409
  • 2
  • 39
  • 70