Pylerno
English

Modules and imports

Find existing functionality and make its origin visible.

On this page

The concept

A module groups reusable Python code. import math binds the module name, so its square-root function is called as math.sqrt. A from import binds a selected name directly. An alias changes the local name used to refer to an imported module; it does not change the module itself.

The standard library comes with Python. Third-party packages are installed separately. Keep imports near the top of the file and avoid wildcard imports, which make the origin of names harder to determine.

Worked example

python
import datetime as dt
import math
from statistics import mean

print(math.sqrt(81))
print(math.pi)
print(mean([70, 80, 90]))
print(dt.date(2026, 1, 15).isoformat())

Trace the result

  1. math supplies sqrt and pi.
  2. statistics supplies mean directly under its own name.
  3. datetime is locally named dt and constructs a fixed date for reproducible output.
text
9.0
3.141592653589793
80
2026-01-15
Line-by-line walkthrough

Line 1: import datetime as dt

Load datetime (calendar dates, timestamps, and durations). Importing makes these names available; it is not a call to every function in the module.

Line 2: import math

Load math (mathematical operations and finite-number checks). Importing makes these names available; it is not a call to every function in the module.

Line 3: from statistics import mean

Import mean from statistics. This supplies statistical summary functions. The caller can now use the imported names directly.

Line 5: print(math.sqrt(81))

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 6: print(math.pi)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 7: print(mean([70, 80, 90]))

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 8: print(dt.date(2026, 1, 15).isoformat())

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

A local file named json.py or random.py can shadow the standard module you meant to import.

Check your understanding

What does this program print?

python
import math
print(math.isqrt(15))
Choose one answer

Search documentation

Share this page