In this lesson, you will learn how to organize your project dependencies into core requirements and optional "extras" to keep environments lean and tailored to specific user needs.
Why Use Extras?
As your project grows, not every user needs every library. For example, if you are building a data processing tool, most users need pandas, but perhaps only a small subset needs matplotlib for visualization or sqlalchemy for database storage. Instead of forcing everyone to download every dependency, you can define optional feature sets known as "extras."
Defining Extras in pyproject.toml
Using the standard pyproject.toml file, you categorize these dependencies under the [project.optional-dependencies] table. This structure keeps your base environment lightweight while allowing for "on-demand" installations.
[project]
name = "my-data-tool"
version = "0.1.0"
dependencies = [
"pandas>=2.0.0",
]
[project.optional-dependencies]
viz = [
"matplotlib>=3.7.0",
"seaborn>=0.12.0",
]
db = [
"sqlalchemy>=2.0.0",
]
Installing Optional Features
When a user installs your package, they can choose which extras to include using bracket notation. If a developer wants the full suite of features, they can install all of them at once:
- Install core only:
pip install . - Install with visualization:
pip install ".[viz]" - Install with everything:
pip install ".[viz,db]"
This approach provides a professional, "à la carte" experience for your users. It prevents "dependency bloat," where users are forced to manage dozens of unused libraries, and it makes your project much easier to maintain in restricted environments like CI/CD pipelines or lightweight Docker containers. By strictly separating what is required to run the core logic from what is optional for specific use cases, you ensure that your project remains modular, efficient, and user-friendly.
Key Takeaway: Use the optional-dependencies table in pyproject.toml to define modular feature sets, allowing users to install only the components they actually need for their specific workflows.