A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.
1. What is a package?
While a module is a single .py file, a package is a directory containing multiple .py files. It helps you organize your project logically as it grows larger.
For example, a Sound package might look like this:
Sound/
__init__.py
Formats/
__init__.py
wavread.py
wavwrite.py
Effects/
__init__.py
echo.py
surround.py
2. Create package (__init__.py)
To make Python treat a directory as a package, it must contain a file named __init__.py.
This file can be empty, but it is often used to execute initialization code for the package or set the __all__ variable to define what gets imported when from package import * is used.
Note: As of Python 3.3+, __init__.py is technically optional (creating a “Namespace Package”), but it is still considered best practice for regular packages.
3. Import from package
You can import modules from a package using the dot . operator.
# Import a specific module
import Sound.Effects.echo
# You must use the full name to access its functions
Sound.Effects.echo.add_echo("Hello", delay=0.5)
An alternative (and often cleaner) way:
from Sound.Effects import echo
echo.add_echo("Hello", delay=0.5)
Or importing a specific function directly:
from Sound.Effects.echo import add_echo
add_echo("Hello", delay=0.5)
4. Subpackages
Packages can contain nested directories, which are called subpackages (like Formats and Effects in the example above).
You can use relative imports to interact between modules inside the same package. These use leading dots:
.means current package..means parent package
Inside Sound/Effects/surround.py, you could write:
# Import from the same subpackage
from . import echo
# Import from a sibling subpackage
from ..Formats import wavread
Relative imports ensure that if you rename your top-level package, the internal imports do not break.
Discussion
Loading comments...