In this lesson, you will learn how to ensure your Python package includes essential non-code files, such as configuration templates, HTML, or media assets, when you build and distribute your project.
The Challenge of Non-Code Resources
By default, modern build backends (like Hatch or Flit) are designed to package your .py files. However, if your application relies on a config.yaml file or a logo.png image, these files are often ignored during the build process because they aren't part of the Python module structure. To make them available to your code at runtime, you must explicitly tell your build system to include them in the distribution package.
Configuring pyproject.toml
The standard way to manage these assets is through the [tool.setuptools.package-data] or equivalent sections in your pyproject.toml. This allows you to define explicit inclusion rules.
If you are using setuptools, you can map your package to specific file patterns:
[tool.setuptools.package-data]
my_package = [
"templates/*.html",
"assets/config.yaml",
"data/*.csv",
]
In this example, the build backend will look inside your my_package directory and include everything matching those patterns in the final distribution (the wheel).
Why Use Explicit Inclusion?
Explicitly defining these paths prevents "bloat." If you simply included every file in your project folder, you might accidentally package hidden .git directories, local logs, or virtual environment files into your final distribution. By listing exactly what you need, you ensure your package remains lightweight and secure.
Once packaged, your application code can locate these files reliably. Instead of using hardcoded relative paths (which break depending on where the user runs the script), you should use the importlib.resources module (available in the standard library) to access these files at runtime, treating them as data streams associated with your package.
Key Takeaway: You must explicitly define non-code assets in your pyproject.toml configuration to ensure they are bundled into your distribution package; otherwise, your application will fail to find these critical files when installed by end-users.