Learn how to create, import, and organize Python modules. Master packages, __name__, __init__.py, and module best practices for cleaner code.
📌 Python modules, import module, create module, Python packages, __init__.py, module organization
A module in Python is simply a file with a .py extension containing Python code—functions, classes, and variables—that can be imported and reused across programs. Modules are the cornerstone of code organization in Python.
Modules provide four critical benefits: organizing related code into separate files, enabling code reuse across multiple programs, preventing name conflicts through namespaces, and dramatically improving code readability and maintainability.
Creating a module is as simple as saving Python code in a .py file. Here's a basic module example saved as mymath.py: it contains a PI constant and two functions—add() for addition and divide() for division with zero-check protection.
Python offers four primary import methods. The full import (import mymath) requires accessing functions via dot notation like mymath.add(). Specific imports (from mymath import add) bring individual functions directly into the namespace. Aliasing (import mymath as mm) creates shorter references. The wildcard import (from mymath import *) brings everything but is discouraged due to namespace pollution.
Packages extend modules by organizing multiple modules into directory hierarchies. A package is any directory containing an __init__.py file that signals Python to treat it as a package. Packages enable deep organization like mypackage/subpackage/module3.py.
# mymath.py
"""Module with mathematical functions."""
PI = 3.14159
def add(a, b):
"""Addition of two numbers."""
return a + b
def divide(a, b):
"""Division with zero-check."""
if b == 0:
raise ValueError("Division by zero is not possible")
return a / b# Full import import mymath result = mymath.add(5, 3) print(result) # 8 # Specific imports from mymath import add, divide result = add(10, 5) print(result) # 15 # With aliasing import mymath as mm area = mm.PI * (5 ** 2) print(area) # 78.53975
# Directory structure
mypackage/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
├── __init__.py
└── module3.py
# Import from package
from mypackage import module1
from mypackage.subpackage import module3# mymodule.py
def main_function():
print("Main logic here")
# Only runs when executed directly, not when imported
if __name__ == "__main__":
print("Running as script")
main_function()# mymodule.py
__all__ = ['public_function', 'PublicClass']
def public_function():
"""This will be imported with import *"""
pass
def _private_function():
"""This won't be imported with import *"""
pass
class PublicClass:
pass