Python Modules
Organize code into modules with import, from-import, __name__, and the standard library.
What you'll learn
- Create and import your own modules
- Use import and from-import syntax
- Understand the if __name__ == '__main__' guard
- Explore key standard library modules
- Control what gets exported with __all__
Concept
What Is a Module?
A module is simply a .py file. The filename becomes the module name. Modules let you organize code into reusable files instead of one giant script:
project/
├── main.py
├── utils.py ← this is a module named "utils"
└── models.py ← this is a module named "models"
Any Python file can be imported as a module. This is the foundation of code organization in Python — you split your program into logical files and import from them.
Importing
There are several import styles, each with different trade-offs:
# Import the whole module — must qualify with module name
import math
print(math.pi)
print(math.sqrt(16))
# Import specific names — no qualification needed
from math import pi, sqrt
print(pi)
print(sqrt(16))
# Import with an alias — useful for long names
import numpy as np
import datetime as dt
# Import everything (discouraged — pollutes namespace)
from math import *
Best practice: use import module or from module import specific_name. Avoid from module import * — it pollutes your namespace and makes it unclear where names came from, which can cause subtle bugs.
Creating Your Own Module
Save this as utils.py:
# utils.py
def greet(name):
return f"Hello, {name}!"
def double(x):
return x * 2
PI_APPROX = 3.14159
Then in main.py in the same directory:
# main.py
import utils
print(utils.greet("Ada")) # Hello, Ada!
from utils import greet, double
print(double(21)) # 42
Python looks for modules in the directories listed in sys.path — the current directory is usually first, which is why local modules are found automatically.
The __name__ Guard
Every module has a __name__ attribute. When you run a file directly, __name__ is "__main__". When it is imported, __name__ is the module name:
# mymodule.py
def main():
print("Running the program")
if __name__ == "__main__":
# This only runs when the file is executed directly
# NOT when it is imported
main()
This guard lets your file serve double duty: as a runnable script (python mymodule.py) and as an importable module (import mymodule). Without it, the code would run on import too, which is usually not what you want.
__all__ — Controlling Exports
Define __all__ in your module to specify what from module import * exports:
# utils.py
__all__ = ["greet", "double"] # only these are exported with *
def greet(name):
return f"Hello, {name}!"
def double(x):
return x * 2
def _internal():
pass # not exported — "private" by convention
Names starting with _ are also excluded from import * by convention. __all__ gives you explicit control over your module's public API.
Key Standard Library Modules
Python's "batteries included" standard library is one of its greatest strengths:
os— operating system interface (paths, env vars, processes)sys— interpreter-specific functions (argv, exit, path)math— mathematical functions and constantsdatetime— date and time manipulationjson— JSON encoding and decodingre— regular expressionscollections— specialized containers (Counter, defaultdict, namedtuple)itertools— efficient iteration utilitiespathlib— object-oriented path handlingrandom— random number generationlogging— flexible logging system
import os, sys, math, random
from collections import Counter
print(os.getcwd()) # current working directory
print(sys.version) # Python version
print(math.factorial(5)) # 120
print(random.randint(1, 100)) # random int 1-100
print(Counter("aabbbcccc")) # Counter({'c': 4, 'b': 3, 'a': 2})
You rarely need to install external packages for common tasks — check the standard library first.
Example
# --- Imagine this is saved as utils.py ---
# def greet(name):
# return f"Hello, {name}!"
# def double(x):
# return x * 2
# PI_APPROX = 3.14159
# --- This is main.py ---
# Importing the standard library
import math
import random
import sys
from collections import Counter, defaultdict
from datetime import datetime
# math module
print(f"Pi: {math.pi:.4f}")
print(f"Factorial 5: {math.factorial(5)}")
print(f"GCD of 12 and 18: {math.gcd(12, 18)}")
# random module
print(f"Random int 1-100: {random.randint(1, 100)}")
print(f"Choice: {random.choice(['apple', 'banana', 'cherry'])}")
# collections module
word_count = Counter("the quick brown fox jumps over the lazy dog the")
print(f"Top 3 words: {word_count.most_common(3)}")
# defaultdict — no KeyError for missing keys
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dict(dd))
# sys module
print(f"Python version: {sys.version_info.major}.{sys.version_info.minor}")
# datetime module
now = datetime.now()
print(f"Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# The __name__ guard pattern
if __name__ == "__main__":
print("This runs only when executed directly, not on import")
Demonstrates importing and using standard library modules: math (pi, factorial, gcd), random (randint, choice), collections (Counter, defaultdict), sys (version), and datetime. The __name__ guard at the bottom shows the standard pattern.
Try it
- JSON Formatter
The json module is one of the most used standard library modules.
- Regex Tester
The re module provides regex — test patterns used in Python code.
Common mistakes
The mistake
Using 'from module import *' which pollutes the namespace
The fix
Wildcard imports make it unclear where names come from and can cause name collisions. Use 'import module' or 'from module import specific_name'. If you must use *, define __all__ in the module to control exports.
The mistake
Forgetting the if __name__ == '__main__' guard in scripts that are also modules
The fix
Without the guard, code runs on import too. Always wrap script-execution code in 'if __name__ == "__main__":' so the file can be both run directly and imported as a module without side effects.
Related Resources
Related Cheatsheets
- Python Cheatsheet
Import syntax, standard library overview, and __name__ guard.
Practice Python Modules
5 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.