06.1 - Modules & Imports
What is a Module?
A module is any Python file (.py). When you import it, Python executes it and makes its contents available.
# math_utils.py
PI = 3.14159265
def circle_area(radius):
return PI * radius ** 2
def circle_perimeter(radius):
return 2 * PI * radius
# main.py — importing the module
import math_utils
math_utils.circle_area(5) # 78.54...
math_utils.PI # 3.14159265
Import Styles
# 1. Import the whole module
import math
math.sqrt(16) # 4.0
math.pi # 3.14159...
# 2. Import specific names
from math import sqrt, pi
sqrt(16) # 4.0 (no prefix needed)
# 3. Import with alias
import numpy as np
from datetime import datetime as dt
# 4. Import all (avoid!)
from math import * # pollutes namespace
| Style | When to use |
|---|---|
import module | When you use many things from the module |
from module import name | When you only need a few specific names |
import module as alias | For long names (numpy as np) |
from module import * | Almost never — pollutes namespace |
The Standard Library
Python ships with an enormous standard library — "batteries included":
| Module | Purpose |
|---|---|
os | OS interface — paths, env vars, processes |
sys | Python runtime — argv, path, exit |
pathlib | Object-oriented filesystem paths |
re | Regular expressions |
json | JSON encode/decode |
csv | CSV read/write |
datetime | Dates and times |
collections | Specialized containers |
itertools | Iterator tools |
functools | Higher-order function tools |
math | Mathematical functions |
random | Random number generation |
hashlib | Cryptographic hashes |
logging | Application logging |
unittest | Unit testing |
argparse | CLI argument parsing |
How Python Finds Modules
Python searches for modules in this order:
- Current directory (or script's directory)
- Directories in
PYTHONPATHenvironment variable - Standard library
- Site-packages (installed packages)
import sys
print(sys.path) # Shows the search path
__all__ — Public API
__all__ defines which names are exported when someone does from module import *:
# mymodule.py
__all__ = ["public_func", "PublicClass"]
def public_func():
return "I'm public"
def _private_func(): # not in __all__
return "I'm private"
class PublicClass:
pass
if __name__ == "__main__":
# utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
if __name__ == "__main__":
# This only runs when utils.py is executed directly
# NOT when it's imported
print(add(10, 5)) # 15
print(subtract(10, 5)) # 5
Lazy Imports and Performance
# Import heavy modules only when needed
def parse_yaml(data):
import yaml # imported only when function is called
return yaml.safe_load(data)
Key Vocabulary
| Term | Definition |
|---|---|
| Module | A .py file — the basic unit of code organization |
| Package | A directory containing __init__.py and multiple modules |
sys.path | List of directories Python searches for modules |
__name__ | "__main__" when run directly, module name when imported |
__all__ | List of public names exported from a module |
| Alias | Short name for a module: import numpy as np |
| Standard library | Built-in modules shipped with Python |
Summary
- Every
.pyfile is a module — import withimport nameorfrom name import x - Prefer
import modulefor multiple uses,from module import funcfor specific items - Avoid
from module import *— it pollutes the namespace __all__defines the public API of a moduleif __name__ == "__main__":separates runnable code from importable code
📄️ 06.1 - Modules & Imports
Organize code with Python modules, understand import mechanics, absolute vs relative imports, and the __all__ convention
📄️ 06.2 - Creating Packages
Build a Python package with __init__.py, submodules, and a proper directory structure
📄️ 06.3 - Virtual Environments & pip
Isolate project dependencies with venv, manage packages with pip, and use requirements.txt and pyproject.toml
📄️ Lab - Module 06
Create a properly structured Python package with modules, __init__.py, and a virtual environment
📄️ Quiz - Module 06
30 questions on modules, packages, imports, virtual environments, and pip