Table of contents
What is a Package?
A Python package is a way of organizing related modules into a directory hierarchy.
Essentially, it's a directory that contains multiple Python modules along with a special __init__.py
file which allows the directory to be recognized as a package by Python.
Packages provide a method of grouping related Python code into a namespace.
The namespace provided by a package helps prevent naming clashes between different areas of functionality.
When you import a package, Python searches through the directories on sys.path
looking for the package subdirectory.
Base example
Let's create the following project structure:
š my_project/
āāā š my_math/
ā āāā š __init__.py
ā āāā š add.py
ā āāā š sub.py
āāā š main.py
In the my_math
package, we have two modules: add.py
and sub.py
.
The __init__.py
file is required to make Python treat the my_math
directory as a package.
def add(a, b):
return a + b
def sub(a, b):
return a - b
from .add import add
from .sub import sub
Note: If you leave __init__.py
empty, Python will still recognize the directory as a package;
this allows you to import modules from this package.
from my_math import add, sub
print(add(1, 2)) # 3
print(sub(3, 1)) # 2
or
import my_math
print(my_math.add(1, 2)) # 3
print(my_math.sub(3, 1)) # 2
Now instead of having all the code in one file, we have separated the code into different modules.
Moreover, we have grouped the modules into a package called my_math
.
Instead of importing the functions directly from the modules, we import them from the package.
Packages help to keep Python code organized, reusable, and clear to both the original developer and others who may use their code. They are a fundamental part of structuring Python applications.