Course contentsShow
← Python
Lesson 528 of 1,0608. Professional Tooling and PackagingFree lesson

Configuring Package Discovery and Inclusion

Use include and exclude patterns to control precisely which source files and data assets are bundled into your distribution.

In this lesson, you will learn how to use explicit include and exclude patterns in your pyproject.toml to precisely control which files and directories are bundled into your package distribution.

Why Control Inclusion?

By default, modern build backends (like Hatch, Flit, or PDM) often use "auto-discovery," which attempts to guess which files belong in your package. While convenient, this can accidentally include sensitive configuration files, massive local test logs, or temporary build artifacts. Explicitly configuring what gets included ensures your distribution remains lean, secure, and predictable.

Configuring with pyproject.toml

If you are using a tool like Hatch, you define these rules within the [tool.hatch.build.targets.wheel] section. You can use glob patterns to target exactly what you need.

Consider this project structure:

my_project/
├── src/
│   └── my_pkg/
│       ├── __init__.py
│       └── data.json
├── tests/
├── docs/
└── secret_notes.txt

To ensure only the core package and necessary data files are bundled—while explicitly ignoring the documentation or random text files—you would configure your pyproject.toml like this:

[tool.hatch.build.targets.wheel]
packages = ["src/my_pkg"]

[tool.hatch.build.targets.wheel.force-include]
"src/my_pkg/data.json" = "my_pkg/data.json"

# Alternatively, use exclude patterns:
[tool.hatch.build.targets.wheel]
exclude = [
  "**/secret_notes.txt",
  "docs/",
  "tests/"
]

How It Works

  • Include Patterns: These act as a whitelist. If you find your build is missing a critical asset (like a template folder or a data file), you explicitly list it to ensure it survives the transition from your development environment to the final distribution.
  • Exclude Patterns: These act as a blacklist. This is particularly useful for excluding large directories like tests/ or .git/ directories that aren't needed by the end user and only serve to bloat the wheel file.

By mastering these patterns, you stop relying on the build backend's "best guess" and take full ownership of your distribution’s contents.

Key Takeaway: Use explicit include and exclude patterns to guarantee that your package contains exactly what is required for production, keeping your distribution minimal and secure.