Lesson 15: Modules, Packages & Imports
Organize code into files, import between them, use the __name__ guard, and install packages with pip.
Modules — Code in Files
A module is simply a .py file. Anything you can run, you can import: functions, classes, variables. When a file is imported, its top-level code runs once, and its names become available to the importer.
# math_helper.py
def square(x):
return x ** 2
# main.py
import math_helper
print(math_helper.square(5)) # 25
Modules are how Python stays organized. Every library you pip install is ultimately a collection of modules — and your own projects should be too.
What You'll Learn in This Lesson
- Import modules with all four import styles
- Understand packages — folders of modules
- Use the
__name__guard to make files both script + library - Install third-party packages with pip
Import Styles
| Style | Usage | Example |
|---|---|---|
import module |
module.name |
import math → math.sqrt(16) |
from module import name |
name directly |
from math import sqrt → sqrt(16) |
from module import a, b |
Several names | from math import pi, sqrt |
import module as m |
Alias | import math as m → m.sqrt(16) |
Which to use? import module keeps the namespace explicit (no name clashes). from module import name is shorter but can clash. Alias imports are great for long names like import matplotlib.pyplot as plt.
A warning on star imports: from module import * dumps every public name into your namespace — it can silently overwrite your variables and is banned in most professional style guides.
Packages — Folders of Modules
A package is a folder of modules containing an __init__.py file (even an empty one) that marks the folder as importable:
my_project/
├── __init__.py
├── main.py
└── utils/
├── __init__.py
└── strings.py
from utils.strings import clean_text
Big projects are organized as packages — one folder per feature, modules inside.
The __init__.py file can be empty (just a marker) or it can pre-import convenient names so users write from utils import clean_text instead of the deeper path. In Python 3.3+, packages without __init__.py (namespace packages) also work — but explicit is better.
The name Guard — Script + Library in One File
if __name__ == "__main__": runs a block only when the file is executed directly, not when imported:
def square(x):
return x ** 2
if __name__ == "__main__":
# Runs only when: python math_helper.py
print("square(5) =", square(5))
- Direct run:
__name__is set to"__main__"→ block runs. - Imported:
__name__is set to the module name → block skipped.
This lets every file be both a runnable script and a safe importable library.
Mental model:
__name__is a magic variable that answers "how was this file started?" If the answer is "as the main program", run the demo code. If "as a library", stay quiet and only offer the functions.
pip — The Package Installer
Third-party packages are installed with pip:
pip install requests
pip install numpy pandas matplotlib
Virtual environments keep each project's dependencies isolated — the professional standard:
python -m venv .venv # create
source .venv/bin/activate # activate (Windows: .venv\Scripts\activate)
pip install requests # install into THIS project only
Never pip install globally — different projects need different versions.
Why virtual environments are non-negotiable in 2026:
- Project A needs pandas 2.0; Project B needs pandas 1.5. Globally installed, they fight.
- A corrupted global environment can break your whole machine's Python.
requirements.txt+ venv = anyone can reproduce your exact environment:pip install -r requirements.txt.
Common Mistakes to Avoid
- Mistake: Importing a module whose name shadows a built-in (e.g.,
math.pyin your project) — Fix: rename your file. - Mistake: Circular imports (A imports B, B imports A) — Fix: move shared code to a third module or import inside functions.
- Mistake: Putting executable code at module top level — Fix: wrap it in
if __name__ == "__main__":. - Mistake:
from module import *polluting the namespace — Fix: import explicitly or by module name. - Mistake: Installing packages globally instead of in a venv — Fix: create and activate a virtual environment per project.
Professional Tips & Tricks
- Import at the top of the file, one import per line, in a consistent order (stdlib, third-party, local).
- Always guard executable code with
if __name__ == '__main__':so it can be imported safely. - Use relative imports (
from . import utils) inside packages. - Freeze your dependencies with
pip freeze > requirements.txtfor reproducibility. - Alias long library names:
import pandas as pd,import numpy as np.
Key Takeaways
- A module is a
.pyfile; a package is a folder of modules with__init__.py. - Four import styles: direct, from-import, multi-name, alias.
- The
__name__guard makes files script + library. pip installadds packages; virtual environments isolate them.- Keep imports at the top and guard executable code.
Next up: Module 5 — object-oriented programming with classes.
# math_helper.py
def square(x):
"""Return x squared."""
return x ** 2
def cube(x):
"""Return x cubed."""
return x ** 3
if __name__ == "__main__":
# Runs only when executed directly, not when imported
print("Running math_helper directly")
print("square(5) =", square(5))Lesson Code (Python)
# math_helper.py
def square(x):
"""Return x squared."""
return x ** 2
def cube(x):
"""Return x cubed."""
return x ** 3
if __name__ == "__main__":
# Runs only when executed directly, not when imported
print("Running math_helper directly")
print("square(5) =", square(5))Console Output
Running math_helper directly
square(5) = 25Code Visualization Tips
- Picture modules as library shelves: import pulls the right book (file) off the shelf.
- Picture packages as shelves inside a room: folder -> modules -> names.
- Trace the __name__ trick: direct run sets __name__ to '__main__'; import sets it to the module name.
Professional Tips & Tricks
- Import at the top of the file, one import per line, in a consistent order (stdlib, third-party, local).
- Always guard executable code with if __name__ == '__main__': so it can be imported safely.
- Use relative imports (from . import utils) inside packages.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Problem 1: Math Module Pipeline 1
Test Your Knowledge
Instant feedbackQuick Check: Lesson 15: Python Modules, Packages, Virtual Environments & Pip
Up next · Continue learning
Classes, Instances & Inheritance
Object structure, __init__ constructor, instance parameters, methods, and parent-child overrides.