Python Modules
A module is simply a .py file containing Python code — functions, classes and variables — that other code can import and reuse. Modules keep big programs organised, and they're how you tap into Python's enormous standard library.
Importing a module
import math
print(math.sqrt(81))
print(math.pi)
print(math.floor(7.8))9.0
3.141592653589793
7
After import math, everything in the module is reached through the math. prefix. This namespace keeps names from colliding: your own floor variable won't clash with math.floor.
Import styles
| Form | Use it as | Notes |
|---|---|---|
import math |
math.sqrt(2) |
clearest; recommended default |
import statistics as st |
st.mean(data) |
alias for long names |
from math import sqrt, pi |
sqrt(2) |
import specific names |
from math import * |
sqrt(2) |
imports everything — avoid, it hides where names come from |
import statistics as st
from math import sqrt, pi
from collections import Counter
scores = [72, 85, 90, 85, 64]
print(st.mean(scores), st.median(scores))
print(round(sqrt(2), 4), round(pi, 2))
print(Counter("mississippi").most_common(2))79.2 85
1.4142 3.14
[('i', 4), ('s', 4)]
Creating your own module
Save some code in a file, for example greetings.py:
# greetings.py
DEFAULT_NAME = "friend"
def hello(name=DEFAULT_NAME):
return f"Hello, {name}!"
def goodbye(name=DEFAULT_NAME):
return f"Goodbye, {name}."Any other file in the same folder can now import it, using the file name without .py:
# main.py
import greetings
from greetings import goodbye
print(greetings.hello("Vinh"))
print(goodbye())python3 main.pyHello, Vinh!
Goodbye, friend.
Note: Each playground on this site is a single file, so the multi-file example above is shown rather than run. Try it on your own computer.
if __name__ == "__main__":
When Python runs a file directly, it sets that module's __name__ to "__main__". When the file is imported, __name__ is the module's name instead. This lets a file act both as a reusable module and as a script:
# geometry.py
def area(r):
return 3.14159 * r * r
if __name__ == "__main__":
# runs only when this file is executed, not when imported
print("Self-test:", round(area(2), 2))Running the file directly executes the self-test; importing it from another file does not:
python3 geometry.py
python3 -c "import geometry; print(geometry.area(1))"Self-test: 12.57
3.14159
Exploring a module
dir() lists the names a module defines, and help() prints its documentation. Many modules also have a version or a docstring:
import string
public = [name for name in dir(string) if not name.startswith("_")]
print(public[:6])
print(string.ascii_lowercase)
print(string.digits)['Formatter', 'Template', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords']
abcdefghijklmnopqrstuvwxyz
0123456789
Packages
A package is a folder of modules. It's how larger libraries are organised, and you import from it with dotted names:
shop/
__init__.py
cart.py
payments/
__init__.py
card.pyfrom shop.cart import Cart
from shop.payments import cardThe standard library uses packages too — os.path, json.decoder, urllib.request.
import os.path
from urllib.parse import urlparse
print(os.path.splitext("report.final.pdf"))
url = urlparse("https://example.com:8080/docs/page?lang=en")
print(url.hostname, url.port, url.path, url.query)('report.final', '.pdf')
example.com 8080 /docs/page lang=en
Where does Python look for modules?
When you import name, Python searches, in order: the folder of the script being run, the folders in the PYTHONPATH environment variable, and the standard library and installed packages (site-packages). The full list lives in sys.path.
Tip: Never name your own file after a module you want to use — a
random.pyorjson.pyin your project folder will be imported instead of the real one!
A tour of useful standard modules
| Module | For |
|---|---|
math, statistics |
maths and basic stats |
datetime |
dates and times |
json, csv |
data formats |
re |
regular expressions |
os, pathlib, shutil |
files and folders |
collections, itertools, functools |
extra data structures and tools |
random |
random numbers |
urllib, http |
web requests and servers |
Test yourself
After from math import sqrt, how do you call the square-root function?
- math.sqrt(9)
- sqrt(9)
- math::sqrt(9)
- import.sqrt(9)
What is __name__ when a file is run directly as a script?
- The file name
- "__main__"
- "script"
- None
What is a package?
- A single .py file
- A compiled module
- A folder of modules that can be imported with dotted names
- A pip command