Packages
A package in Python is a directory that contains a collection of modules along with a special file called __init__.py. Packages let you organize related mo...
Python Packages: Organizing Modules into Namespaces
A package in Python is a directory that contains a collection of modules along with a special file called __init__.py. Packages let you organize related modules under a common namespace, which is essential for building large projects or distributing reusable libraries.
The __init__.py file marks a directory as a Python package. It can be completely empty, which simply enables the directory to be treated as a package, or it can contain initialization code that runs when the package is imported. In modern Python (3.3 and later), you can also create namespace packages without __init__.py, but the file is still common and expected in many projects.
Here is a typical package structure for a small project:
myapp/ __init__.py database/ __init__.py connection.py queries.py utils/ __init__.py formatting.py validation.py main.py
To import from a nested package, you use dotted notation:
from myapp.database.connection import connect from myapp.utils.formatting import format_date
The __init__.py file in each package can import names from its sub-modules to make them accessible at the package level. For example, if database/__init__.py contains from .connection import connect, then callers can write from myapp.database import connect instead of the longer form.
Relative imports use dots to refer to the current or parent package. A single dot means the current package, and two dots mean the parent package:
# Inside myapp/database/queries.py from .connection import connect # same package from ..utils.validation import validate # parent then utils
Packages are the foundation of Python's ecosystem. When you install a third-party library with pip install requests, you are installing a package that you then import as a regular module. The package contains multiple modules organized in directories, and the package's __init__.py controls what is publicly exposed.
Exam tip: Know the difference between a module (a single .py file) and a package (a directory with __init__.py). Also understand that from package import module imports the module object itself, while from package.module import function imports a specific name from a specific file. These distinctions appear frequently in exam questions about Python's import system.