Sub topic 1
What the standard library gives you and how to import it
Python ships with a large set of modules known as the standard library. This tutorial covers three of them: math, random, and datetime. This chapter explains how Python finds and loads a module, how the different import forms change the names in your code, and which mistakes to avoid. Later chapters rely on all of it.
Prerequisites
This chapter assumes you can already:
- Write and call functions and use
if,for, andwhile. - Work with lists and strings.
- Run a script (
python script.py) or use the interactive interpreter (python).
You do not need to install anything. The modules in this tutorial come with Python 3.9 or later. zoneinfo, used in a later chapter, was added in 3.9.
What the standard library is
The standard library is the collection of modules installed with Python itself. A module is a file or compiled unit of code that defines names such as functions, classes, and constants. You get access to those names with an import statement.
The standard library is useful for three reasons:
- It is available wherever Python is installed, so your code has no extra dependencies.
- It is maintained alongside the language, so behavior is documented and changes follow Python's release policy.
- Its code has been used and tested by a very large number of people.
The standard library is not always the best tool. Specialized third-party packages such as NumPy (arrays and fast numeric work) can do more or run faster. The standard library is the right default when you need a small, dependable tool and want no installation step.
The three modules in this tutorial
| Module | What it provides | Typical use |
|---|---|---|
| `math` | Constants and functions for real numbers, plus integer helpers | Square roots, rounding, counting problems |
| `random` | Pseudo-random number generation | Simulations, games, sampling, shuffling |
| `datetime` | Date, time, and duration types | Calendars, deadlines, timestamps, time zones |
A closely related module, secrets, appears in a later chapter. It covers the case where random is the wrong choice.
The four import forms
Python has several ways to bring a name into your program. Each one decides what you type later and what can collide with other names.
Import the module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793This binds one name, math, in your file. Every use is written math.something, so a reader can see where each function came from. This is the form this tutorial uses most.
Import specific names
from math import sqrt, pi
print(sqrt(16)) # 4.0
print(pi) # 3.141592653589793This binds sqrt and pi directly. The code is shorter, but you lose the prefix that tells readers where sqrt came from.
Import with an alias
import math as m
print(m.floor(-2.5)) # -3An alias gives the module a new local name. It is common for long names in third-party code (import numpy as np). For short modules like math it usually makes the code harder to read.
Import everything
from math import *This copies every public name from the module into your file. Avoid it. You cannot tell where a name came from, and a later import can silently replace an earlier name. Linters flag it for that reason.
Choosing a form
| Situation | Preferred form |
|---|---|
| Using many different functions from a module | `import module` |
| Using one or two names many times in a short script | `from module import name` |
| Two modules export the same name | `import module` for both, or alias one |
| A module name is long and used constantly | `import module as short` |
| Interactive exploration in a REPL | Any form, including `*`, is acceptable for throwaway work |
A common trap: `datetime` the module and `datetime` the class
The datetime module contains a class that is also named datetime. The two forms below give you different objects under the same word.
import datetime
print(type(datetime)) # <class 'module'>
print(datetime.date(2026, 11, 26)) # 2026-11-26
print(datetime.datetime(2026, 11, 26)) # 2026-11-26 00:00:00from datetime import datetime
print(type(datetime)) # <class 'type'>
print(datetime(2026, 11, 26)) # 2026-11-26 00:00:00
try:
datetime.timedelta(days=1)
except AttributeError:
print("datetime is now the class, not the module")After from datetime import datetime, the name datetime refers to the class. Code written for the module form, such as datetime.timedelta, then fails with AttributeError. Pick one style per file and keep it. Importing the class names explicitly avoids the confusion:
from datetime import date, datetime, timedelta
print(date(2026, 11, 26) + timedelta(days=30)) # 2026-12-26
print(datetime(2026, 11, 26, 14, 30)) # 2026-11-26 14:30:00How an import works
An import statement does more than copy names. Python runs the following steps the first time it sees a module.
Three points follow from this flow:
- Modules load once. The result is cached in
sys.modules. A secondimport mathanywhere in the program reuses the same object, which is cheap. - The search order matters. Python looks at built-in modules first, then the locations in
sys.path. The first entry ofsys.pathis normally the directory of the script you ran. - Importing runs code. Module-level statements execute at first import. This is why a module can set up constants like
math.pi.
You can observe the cache directly:
import sys
import math
import math as m
print("math" in sys.modules) # True
print(m is math) # True
print(sys.modules["math"] is math) # TrueSome standard modules are written in Python and some are compiled into the interpreter. random is a Python file, while math is implemented in C and may have no file at all on some builds. Do not rely on __file__ being present:
import math
import random
print(getattr(math, "__file__", "built in or compiled"))
print(random.__file__.endswith("random.py")) # TrueExploring a module
You do not need to memorize every function. Python can describe itself.
import math
names = [n for n in dir(math) if not n.startswith("_")]
print(names[:5]) # ['acos', 'acosh', 'asin', 'asinh', 'atan']
print(len(names) > 40) # Truedir(module) lists the names a module defines. Filtering out names that start with an underscore removes internal ones. In an interactive session, help(math.hypot) prints the documentation for one function. The official documentation at docs.python.org is more complete, and it states in which version each feature was added.
Common errors and how to read them
ModuleNotFoundError
ModuleNotFoundError: No module named 'maths'The name was not found in built-ins or sys.path. Most often it is a typo (maths instead of math). For third-party packages it means the package is not installed in the environment running the code.
ImportError for a name
ImportError: cannot import name 'sqroot' from 'math'The module exists, but it does not define that name. Check spelling with dir(math).
AttributeError after a successful import
AttributeError: module 'math' has no attribute 'sqroot'The same mistake as above, but with the import math form. The error message names the module, which helps you check the right place.
Shadowing: your file has the same name as a module
Suppose you save your own script as random.py in the folder where you run Python. Because the script directory is first on sys.path, a later import random finds your file instead of the standard one. You may see errors like this:
AttributeError: partially initialized module 'random' has no attribute 'randint'
(most likely due to a circular import)The fix is to rename your file (for example dice_game.py) and delete any __pycache__ folder left beside it. Avoid naming your own files math.py, random.py, datetime.py, secrets.py, or test.py.
Where imports belong
By convention (PEP 8), put imports at the top of the file, one module per line, grouped as standard library, then third-party, then your own modules:
import math
import random
from datetime import date, timedelta
def random_day_in_year(year: int, rng: random.Random) -> date:
start = date(year, 1, 1)
return start + timedelta(days=rng.randrange(365))
print(math.floor(2.7)) # 2
print(random_day_in_year(2026, random.Random(2026)).year) # 2026Imports inside a function are legal. They are used to delay a slow import or to avoid a circular import. For the three modules in this tutorial there is no reason to do that.
Summary of the decision rules
- Prefer
import moduleand qualified names when the source of a name should be obvious. - Use
from module import namewhen the name is distinctive and used often, as withdateandtimedelta. - Never use
from module import *in code you keep. - Do not name your own files after standard modules.
- Read
dir()andhelp()output instead of guessing function names.
Exercise
A script contains from datetime import datetime at the top. Later it calls datetime.timedelta(days=7) and fails with AttributeError. Explain why it fails and show two different ways to fix the imports so that a week from datetime(2026, 11, 26) can be computed.
Show answer
After from datetime import datetime, the name datetime refers to the class, which has no timedelta attribute. The timedelta class lives in the module. Fix 1: import it by name: from datetime import datetime, timedelta, then datetime(2026, 11, 26) + timedelta(days=7). Fix 2: import the module: import datetime, then datetime.datetime(2026, 11, 26) + datetime.timedelta(days=7). Both give 2026-12-03 00:00:00.
Exercise
You saved a practice script as random.py and it contains import random and print(random.randint(1, 6)). It fails when you run it. Why, and what do you change?
Show answer
The script's own directory is first on sys.path, so import random loads your file instead of the standard library module. Your file has no randint defined yet (or is only partly loaded), so the lookup fails. Rename the script to something else, such as dice.py, and remove any __pycache__ folder next to it.
Exercise
Write code that prints how many public names (names not starting with an underscore) the math module defines, and then prints whether math.isclose is among them.
Show answer
``python is not allowed inside this answer, so in words: import math, build names = [n for n in dir(math) if not n.startswith("_")], print len(names), then print "isclose" in names`. The second line prints True on Python 3.5 and later.