Python Modules & Packages: Architecture, Imports & Package Management

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.


1. Creating and Importing a Custom Module

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)

2. The Famous if __name__ == "__main__": Idiom

Every 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))

3. Creating Python Packages (__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

Frequently Asked Questions (FAQ)

Where does Python search for imported modules?

Python searches paths in 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.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!