How can use the 'version' specified in pyproject.toml file in my python typer program?
Asked Answered
S

4

5

i have a very simple python/typer program.

i also use the poetry as build tool.

This is a snippet of my pyproject.toml file:

name = "cat-cli"
version = "0.1.3"
description = "Cat Cli"

Is there a simple way get the version number specified in the toml file into my python program?

Thank you in advance

Sestos answered 30/9, 2022 at 0:23 Comment(0)
V
7

The canonical way of getting the version number of an installed package, is to use importlib.metadata or its backport importlib-metadata if you are on Python <3.8.

try:
    from importlib import metadata
except ImportError:
    import importlib_metadata as metadata

version = metadata.version("mypackage")
Veroniqueverras answered 30/9, 2022 at 5:34 Comment(2)
Is there a good way to retrieve mypackage?Hypoblast
@Hypoblast See my answer below.Kenna
P
1

You could use a package like tomli to read the poetry configuration file and get the version using something like:

import tomli

with open("pyproject.toml", mode="r") as config:
    toml_file = tomli.load(config)

toml_file['tool.poetry']['version'] should get you the version string, assuming you have the tool.poetry table.

Follow this guide to get you started

Phobe answered 30/9, 2022 at 0:33 Comment(0)
U
0

This snippet will show you the include flag to use for arrayobject.h

import numpy as np
import sys
from pathlib import Path

numpy_include_path = Path(np.get_include())
arrayobject_h = numpy_include_path / 'numpy' / 'arrayobject.h'

if arrayobject_h.exists():
    print(f"-I{numpy_include_path}")
else:
    print('arrayobject.h not found :-()')
Unessential answered 21/7, 2023 at 9:57 Comment(0)
K
0
import importlib_metadata as metadata

__version__ = metadata.version(__package__.split(".")[0])

If your file is at the root of the package you may not need to split.

Note that you’ll need to run poetry install for metadata to see the package, or you’ll get

importlib.metadata.PackageNotFoundError: No package metadata was found for PACKAGE_NAME

Kenna answered 15/7, 2024 at 9:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.