Modules and imports
Overview
As programs grow, one long file becomes hard to manage. Modules let you split code across files and reuse it — and they’re also how you use Python’s standard library and the hundreds of thousands of packages other people have written. Every time you’ve written import math, you’ve used a module.
A module is just a .py file
Any Python file is a module. Suppose you have:
# textutils.py
VOWELS = "aeiou"
def count_vowels(text):
return sum(1 for ch in text.lower() if ch in VOWELS)Another file in the same folder can use it:
# main.py
import textutils
print(textutils.count_vowels("banana")) # 3
print(textutils.VOWELS) # aeiouimport textutils runs textutils.py and creates a module object named textutils; everything defined at its top level becomes an attribute: textutils.count_vowels, textutils.VOWELS.
Import styles
import math # use as math.sqrt(2)
from math import sqrt, pi # use as sqrt(2), pi
import statistics as stats # use as stats.mean(...)
from datetime import date as Date # rename a single name| Style | Pros | Cons |
|---|---|---|
import module |
clear where every name comes from | longer to type |
from module import name |
short | can clash with your own names |
import module as alias |
short, still clear | readers must know the alias (common ones: np, pd) |
Avoid from module import *. It dumps every name into your file, so readers can’t tell where anything comes from, and names can silently overwrite each other.
Put imports at the top of the file, standard library first, then installed packages, then your own modules.
How Python finds a module
Python searches, in order:
- the folder of the script you ran;
- the standard library;
- installed packages (the
site-packagesfolder of the current environment).
If it finds nothing:
ModuleNotFoundError: No module named 'requests'— usually meaning the package isn’t installed in the environment you’re running (Virtual environments and packages).
The shadowing trap
Because your own folder comes first, a file called random.py in your project hides the real random module. Then import random imports your file, and you get baffling errors like AttributeError: module 'random' has no attribute 'randint'. Recent Python versions add a hint — “consider renaming … since it has the same name as the standard library module” — but the fix is the same: never name your files random.py, json.py, math.py, email.py, test.py and so on.
Modules run once
The first import of a module runs its code; later imports anywhere in the program reuse the same module object. So module-level code should mostly define things (functions, classes, constants) rather than do things.
if __name__ == "__main__":
Every module has a variable __name__. When you run a file directly, Python sets its __name__ to "__main__"; when the file is imported, __name__ is the module’s name.
That lets one file be both a reusable module and a runnable script:
# textutils.py
def count_vowels(text):
...
if __name__ == "__main__":
# only when run as: python textutils.py
print(count_vowels("banana"))python textutils.py runs the block; import textutils doesn’t. A common layout for scripts is:
def main():
...
if __name__ == "__main__":
main()Packages
A package is a folder of modules. Imports use dotted names:
shop/
├── __init__.py
├── cart.py
└── payments/
├── __init__.py
└── card.pyfrom shop.cart import Cart
from shop.payments import card
import shop.payments.cardThe __init__.py file marks the folder as a regular package (it’s often empty, but code in it runs when the package is imported). Inside a package, modules can import each other with relative imports: from .cart import Cart or from ..utils import slugify.
You can run a module inside a package with python -m shop.cart. The -m flag runs a module by name — which is also how you’ll run tools: python -m pip, python -m venv, python -m pytest.
Exploring a module
import textutils
dir(textutils) # list the names it defines
help(textutils) # its docstrings
textutils.__file__ # where the file isRemember: one file = one module; import at the top; never shadow standard-library names; and guard script code with
if __name__ == "__main__":.
Build your own module
Create two files in the same folder. textutils.py contains a constant VOWELS = "aeiou", a function count_vowels(text) and a function shout(text) that returns the text upper-cased with ! added; at the bottom, an if __name__ == "__main__": block prints a quick self-test. main.py imports the module in two different styles and prints count_vowels("Programming in Python"), shout("hello") and the module’s __name__. Run both files and notice that the self-test only appears when you run textutils.py directly.
# ---- textutils.py ----
VOWELS = "aeiou"
def count_vowels(text):
...
def shout(text):
...
# ---- main.py ----
# import textutils, and also import shout directly# ---- textutils.py ----
"""Small helpers for working with text."""
VOWELS = "aeiou"
def count_vowels(text):
"""Return how many vowels text contains."""
return sum(1 for ch in text.lower() if ch in VOWELS)
def shout(text):
"""Return text in capitals with an exclamation mark."""
return text.upper() + "!"
if __name__ == "__main__":
# Runs only with: python textutils.py
print("Self-test:", count_vowels("banana") == 3, shout("hi") == "HI!")
# ---- main.py ----
import textutils
from textutils import shout
print(textutils.count_vowels("Programming in Python")) # 5
print(shout("hello")) # HELLO!
print(textutils.__name__) # textutilsSummary
- Every
.pyfile is a module;import nameruns it once and gives access to its contents asname.thing. from module import thingimports specific names;import module as aliasshortens long names; avoidfrom module import *.- Python searches the script’s folder, then the standard library, then installed packages — so never name your file after a module you use.
if __name__ == "__main__":runs code only when the file is executed directly, not when it’s imported.- A package is a folder of modules; import from it with dotted names like
from shop.cart import Cart.