Modules and Imports

A module is a Python file that can hold reusable code.

If a file named stats_tools.py contains:

sum(values) adds the numeric items. It is the built-in form of the running total loop from Chapter 3.

another file can import it:

That is the basic idea: move reusable functions out of one script and import them where they are needed.

Imports make names available

This import:

from pathlib import Path

makes the name Path available in the current file.

This import:

import math

makes the module name math available:

print(math.sqrt(9))

The two styles create different names:

ImportName you use
import mathmath.sqrt(9)
from math import sqrtsqrt(9)

Prefer clear imports

For this course, avoid imports that hide where a name came from:

from math import *

That form fills the current file with many names. It is convenient for quick experiments, but it makes code harder to read.

A module should not surprise the importer

When a module is imported, Python runs the top-level code in that module. That means a module should usually define functions and constants at top level, not run a whole program immediately.

Good module shape:

Risky module shape:

Importing the second file would try to read input.txt immediately.

Use a standard-library module

Runs locally with Python in your browser.

Ready to run.

Exercise: Imported name

After this line, which name do you use to call square root?

import math

Answer it first, then check.

HintKeep the module prefix

import math creates the name math; it does not create a separate name sqrt.

SolutionUse math.sqrt

Reach the function through the imported module as math.sqrt. A direct sqrt name would require from math import sqrt instead.