Browse Python Topics ▼
Pick a Web Framework

Modules and Imports in Python

📂 Modules, Packages & Environments 📘 Lesson 38 of 57

Break monolithic code into clean modular files. Master import styles, the __name__ == '__main__' guard, sys.path resolution, and circular import traps.

When you write your first few Python programs, keeping all your code in a single file like main.py is simple and convenient.

At 500 lines of code, however, that single file starts becoming difficult to manage. At 5,000 lines of code, scrolling through a monolithic file to find a specific function is exhausting. If two engineers on your team edit the file simultaneously, resolving git merge conflicts becomes a nightmare.

Python solves this with Modularity: the ability to split your program across multiple independent files.

In Python: Any single file ending in .py is automatically a Module.


1. Creating and Importing Your First Module

Creating a module requires no special configuration. Simply save functions, classes, or constants in a .py file:

# File: calculations.py
"""A module containing shared financial math utilities."""

SALES_TAX_RATE = 0.0825

def compute_total(subtotal):
    return subtotal + (subtotal * SALES_TAX_RATE)

def format_currency(amount):
    return f"${amount:,.2f}"

Now, from any other Python file located in the same directory, you can import and use that logic:

# File: app.py
import calculations

order_price = 150.0
total = calculations.compute_total(order_price)

print("Receipt Total:", calculations.format_currency(total))

Output:

Receipt Total: $162.38

2. The Four Import Styles

Python gives you four distinct ways to import symbols:

Style 1: import module_name (The Cleanest & Safest)

Imports the entire module. You access symbols using the module prefix:

import math
result = math.sqrt(64)

Why it’s great: There is zero ambiguity about where sqrt came from. It prevents accidental name collisions!

Style 2: from module_name import symbol

Imports specific functions or classes directly into your current namespace:

from math import sqrt, pi
print(sqrt(64))
print(pi)

Style 3: import module_name as alias (Aliasing)

Gives the module a shorter or clearer local name:

import calculations as calc
print(calc.SALES_TAX_RATE)

Style 4: from module_name import * (THE DANGEROUS ANTI-PATTERN!)

Wildcard imports dump every single function, class, and variable from that module directly into your local workspace.

[!CAUTION] Never use wildcard imports (import *)! It pollutes your namespace, obscures where functions came from, and silently overwrites existing functions of the same name without warning!


3. The Magic of if __name__ == "__main__":

Look at what happens when Python imports a module: Python executes the entire file from top to bottom!

Suppose calculations.py had a test print at the bottom:

# calculations.py
def compute_total(subtotal):
    return subtotal * 1.08

print("Testing calculations:", compute_total(100))  # OOPS!

When app.py runs import calculations, that test print will execute immediately, spamming your application’s output!

The Solution: The Entry Point Guard

Python provides an internal variable named __name__ that changes depending on how the file is executed:

  • If you run the file directly (python calculations.py): Python assigns __name__ = "__main__".
  • If another file imports the file (import calculations): Python sets __name__ = "calculations".
# calculations.py
def compute_total(subtotal):
    return subtotal * 1.08

if __name__ == "__main__":
    # This block executes ONLY when running `python calculations.py` directly!
    # It is completely ignored when imported by other files!
    print("Self-test mode: 100 with tax =", compute_total(100))

4. How Python Locates Modules: sys.path

When you type import my_module, where does Python look?

Python searches directories in a specific order stored in the list sys.path:

import sys
for path in sys.path:
    print(path)
  1. Current Directory: The folder containing the script you launched.
  2. Standard Library: Built-in modules like math, json, pathlib, os.
  3. Site-Packages: Third-party libraries installed via pip.

If Python checks all paths in sys.path and cannot find the file, it raises a ModuleNotFoundError: No module named 'my_module'.


5. The Circular Import Trap and How to Fix It

A common architecture bug in growing projects is a Circular Import:

  • Module orders.py imports users.py.
  • Module users.py imports orders.py.
orders.py ────────► imports users.py
    ▲                     │
    │                     ▼
    └─────────────── imports orders.py (Incomplete! Crash!)

When this happens, Python halts with: ImportError: cannot import name 'User' from partially initialized module 'users'

How to Fix Circular Imports:

  1. Refactor Shared Types: Move the shared data (e.g. shared constants or data classes) into a neutral third file, such as models.py or constants.py, that both modules can import.
  2. Import Inside the Function: If the import is only needed inside a single function, move the import statement inside that function’s body so it is evaluated on demand rather than at startup.

Summary & What’s Next

  • Every .py file is a reusable module.
  • Always use explicit imports (import math or from math import sqrt); avoid from math import *.
  • Protect executable scripts and self-tests using if __name__ == "__main__":.
  • Python resolves imports using the sys.path search list.

What if your project grows to 50 modules across several categories (like database, authentication, API routes)? Learn how to organize folders of modules using packages.

Test your understanding of Modules and Imports in Python

Quick interactive practice questions with instant feedback.

Take Quiz →