Skip to content

Instantly share code, notes, and snippets.

@kpostekk
Created February 7, 2021 11:27
Show Gist options
  • Save kpostekk/15d735e6fad45cc2547620ea925658d4 to your computer and use it in GitHub Desktop.
Save kpostekk/15d735e6fad45cc2547620ea925658d4 to your computer and use it in GitHub Desktop.
Python package's metadata in json
from .some import dependet_function
from ._version import __version__ # Safely load data

My solution for package versioning in modern python

Credits to this post

Assume this is our project.

code/  # Repo root
  mypkg/  # Package
    __init__.py
    _version.py
    meta.json
  setup.py

If you are here you probably know that you can't directly import __version__ into setup.py. It will raise an error.

To prevent that, we will take some metadata from setup.py and put it into meta.json That will allow to safely share data between package and setup.py because any dependency code won't be executed.

import json
from pathlib import Path
with open(Path(__file__).parent.joinpath('meta.json')) as f:
__meta_json__ = json.load(f)
__version__ = __meta_json__['version']
__author__ = __meta_json__['author']
# https://stackoverflow.com/a/21356350/9256726 and https://stackoverflow.com/a/24293364/9256726
import json
from pathlib import Path
from setuptools import setup
with open(Path('mypkg').joinpath('meta.json')) as f:
__meta_json__ = json.load(f)
setup(
name="mypkg",
packages=["mypkg"],
install_requires=["pyyaml>=5.0.0, httpx>=0.16.1"],
**__meta_json__
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment