Modules and imports
Split code across files and tap into Python's standard library.
- Import from the standard library
- Use import, from-import, and aliases
- Understand how your own files become modules
A module is just a Python file. import lets one file use the functions and
values defined in another — including the vast standard library that ships
with Python. This is the project-shape and abstraction ideas in practice:
organise code into files, and use them through their public names.
Importing
The standard library is full of ready-made tools. Import a module and use its contents with a dot:
import math
math.sqrt(16) # 4.0
math.pi # 3.14159...import vs from-import vs alias
Three forms, each useful:
import random # use as random.choice(...)
from random import choice # bring one name in directly: choice(...)
import statistics as stats # alias a long name: stats.mean(...)from x import y is handy when you use one or two things a lot; plain import x
keeps the source visible (random.choice says where choice came from), which
aids readability.
Your own files are modules too
If you have helpers.py with a function greet, another file imports it by
filename:
# in main.py, next to helpers.py
from helpers import greet
greet("Ada")This is how projects grow beyond one file — each module owns a focused job (cohesion), and others use it through its names (its interface).
Before installing a third-party package, check the standard library — math,
random, datetime, json, pathlib, collections and friends cover an
enormous amount, and they're always available.
Where to go next
That completes Python Core syntax. The intermediate Idioms & structure module goes Pythonic: comprehensions, generators, decorators, classes, and type hints.