osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Embedding version in command-line program


??????? Original Message ???????
On Thursday, October 8, 2020 2:00 PM, Loris Bennett <loris.bennett at fu-berlin.de> wrote:

> Marco Sulla Marco.Sulla.Python at gmail.com writes:
>
> > On Wed, 7 Oct 2020 at 14:16, Loris Bennett loris.bennett at fu-berlin.de
> > wrote:
> >
> > > But the toml file isn't part of the distribution and so it won't be
> > > installed.
> > > I suppose I could write a separate program which parses the toml file
> > > and then just injects the version into init.py.
> >
> > Yes, I do not know poetry, but I suppose you can generate it in its
> > setup. I usually create a separate VERSION file and I read it in
> > init.py. Other people creates a version.py that is evaled inside
> > init.py
>
> I ended up using the module
>
> poetry_version
>
> which allows one to extract the version like this:
>
> import poetry_version
>
> version = poetry_version.extract(source_file=file)
>

It looks to me like that package also just reads the pyproject.toml file.

You could try using the "importlib.metadata" module (https://docs.python.org/3.8/library/importlib.metadata.html). If you're still using python 3.7 (or older) you can install importlib-metadata from PyPI (https://pypi.org/project/importlib-metadata/).

Try putting something like

```
from importlib import metadata

__version__ = metadata.version(__name__)
```
in your __init__.py file.

Then you can do something like:
```
from . import __version__

def main():
    print(f"Version: {__version__}")
```

Bear in mind that this would only work if your package is installed (e.g. in  virtual environment). Otherwise the `metadata.version(__name__)` call will fail with a `importlib.metadata.PackageNotFoundError` exception (of course you could catch that and fall back to trying to read the pyproject.toml file).

--
Heinrich Kruger