Bundling Python Resources

Quick snippet on how to bundle non-python resources in python artifact

How do I ensure non-Python resources such as JSON, YAML, templates, schemas, or static files are actually included when building a Python wheel?

Using setuptools

pyproject.toml

[build-system]
build-system = "setuptools.build_meta"
requires = ]"setuptools"]

[tool.setuptools]
include-package-data = true

[tool.setuptools.package-data]
my_package = [
    "resources/**/*.json",
    "resources/**/*.yaml",
    "templates/**/*.html",
]

Keep the resources inside the package:

my-project/
├── pyproject.toml
└── src/
    └── my_package/
        ├── __init__.py
        ├── code.py
        └── resources/
            ├── config.json
            └── schema.json

Build the artifact:

python -m build

Verify the wheel contains the resources before publishing:

unzip -l dist/*.whl

Then access them through importlib.resources rather than assuming a filesystem-relative path:

from importlib import resources

config = resources.files("my_package") / "resources" / "config.json"