What is a Package?
A package is a directory containing multiple modules and an __init__.py file. Packages help organize related modules into a hierarchical structure, making large projects more manageable.
Creating a Package
Create a directory with an __init__.py file:
mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
The __init__.py File
The __init__.py file makes a directory a package. It can be empty or contain initialization code:
# mypackage/__init__.py
# Empty file - makes directory a package
# Or with initialization
from .module1 import function1
from .module2 import Class1
__version__ = "1.0.0"
Importing from Packages
Import Entire Module
import mypackage.module1
mypackage.module1.some_function()
Import Specific Items
from mypackage.module1 import some_function
some_function()
Import from Subpackage
from mypackage.subpackage.module3 import something
# Or
from mypackage.subpackage import module3
Package Structure Example
mypackage/
__init__.py # Package initialization
config.py # Configuration module
utils/
__init__.py # Subpackage
helpers.py # Helper functions
validators.py # Validation functions
models/
__init__.py # Subpackage
user.py # User model
product.py # Product model
Relative Imports
Use relative imports within packages:
# In mypackage/utils/helpers.py
from .validators import validate_email # Same package
from ..models.user import User # Parent package
from ...config import settings # Grandparent
Package Initialization
Use __init__.py to control what's exported:
# mypackage/__init__.py
from .module1 import public_function
from .module2 import PublicClass
# Only these are available when importing mypackage
__all__ = ['public_function', 'PublicClass']
Installing Packages
Install packages using pip:
# Install from PyPI
pip install package_name
# Install from local directory
pip install /path/to/package
# Install in development mode
pip install -e /path/to/package
Best Practices
- Use __init__.py: Even if empty, it marks directories as packages
- Organize logically: Group related modules together
- Use clear names: Package and module names should be descriptive
- Control exports: Use __all__ to define public API
- Avoid circular imports: Design package structure carefully
Next Steps
Learn about modules first, or explore packaging Python projects for distribution.