As Python software expands to thousands of lines, keeping all code in a single file becomes impossible. Python solves this via Modules and Packages. A module is a single .py file; a package is a directory of modules. Together, they form the foundation of Python's modular architecture.
Create a file named math_utils.py:
# File: math_utils.py
PI = 3.14159
def add(a, b):
return a + b
def circle_area(radius):
return PI * (radius ** 2)
Now import it in another script in the same directory (main.py):
# File: main.py
# 1. Standard module import:
import math_utils
print(math_utils.add(10, 25))
# 2. Specific function import:
from math_utils import circle_area, PI
print("Area of Circle:", circle_area(7))
# 3. Aliasing with 'as':
import math_utils as mu
print(mu.PI)
if __name__ == "__main__": IdiomEvery Python module has a special built-in string variable named __name__:
• When you run the file directly: Python assigns __name__ = "__main__".
• When the file is imported elsewhere: Python assigns __name__ = "math_utils".
# File: calculator.py
def multiply(x, y):
return x * y
# Unit testing code that runs ONLY when executing calculator.py directly:
if __name__ == "__main__":
print("Self-test: 5 * 6 =", multiply(5, 6))
__init__.py)A package is structured as a filesystem folder:
my_ecommerce_app/
│
├── __init__.py # Marks directory as a Python package
├── payment/
│ ├── __init__.py
│ ├── razorpay.py
│ └── stripe.py
└── orders/
├── __init__.py
└── cart.py
You can import from package sub-modules with dot notation:
from my_ecommerce_app.payment.stripe import process_charge
sys.path in this order: (1) The current working directory where the script lives, (2) PYTHONPATH environment variable directories, and (3) Standard library and site-packages where third-party packages installed via pip reside.