Note: Starting with Python 3.3, the __init__.py
file is no longer strictly required to create a package. However, including it is still considered good practice to ensure compatibility and to initialize the package if needed.
A package in Python is a way of organizing related modules into a single directory hierarchy. A package contains a special __init__.py
file to mark the directory as a package.
my_package/
├── __init__.py
├── module1.py
└── module2.py
from my_package import module1
module1.function1()
from my_package.module2 import function2
function2()
import my_package.module1 as m1
m1.function1()
from analytics.statistics import mean
mean.calculate_average()
# utils/__init__.py
from .tools import greet
# tools.py
def greet():
print("Hello")
# main.py
from utils import greet
greet()
from my_package import moduleX
Error: ImportError: cannot import name 'moduleX' from 'my_package'
# Directory without __init__.py
from my_package import module1
Error (in Python < 3.3): ModuleNotFoundError: No module named 'my_package'
from my_package import function1
Error: ImportError: cannot import name 'function1'
from analytics.mean import average
Error: ModuleNotFoundError: No module named 'analytics.mean'
from my_package import module1
Error: ModuleNotFoundError: No module named 'my_package'
import my_package
print(dir(my_package))
Packages provide structure and clarity to Python applications, especially as they scale.