Python Modules, Packages and Environments · Lesson 110 of 149

Python Importing Modules

What you will learn

  • What a module is and why we use them
  • import x, from x import y and as
  • Finding out what a module contains: dir and help
  • Reading import errors
  • Why from x import * is discouraged
  • That a module is loaded once

1. What is a module?

A module is a file of Python code (something.py) that other programs can reuse. Python comes with hundreds of them, called the standard library: math for mathematics, random for random numbers, datetime for dates, json for JSON (lesson 15.7), and so on. Thousands more can be installed (lesson 16.6), and you can write your own (lesson 16.2).

Modules let you:

  • reuse code instead of rewriting it;
  • organise a large program into parts with clear names;
  • keep names separate: two modules may each have a function called load without clashing.

Everything in a module is reached through import.

2. import module

import math

print(math.sqrt(16))
print(math.pi)
print(type(math), math.__name__)
4.0
3.141592653589793
<class 'module'> math

After import math, the name math refers to the module object. You reach its contents with a dot: math.sqrt, math.pi. The dot tells the reader (and Python) exactly where sqrt comes from. The module's own name is in math.__name__.

Quick check: after `import math`, can you write `sqrt(9)` directly?

No. You must write math.sqrt(9), or import the name with from math import sqrt.

3. from module import name

To use a name without the prefix, import it directly:

from math import sqrt, pi

print(sqrt(25), pi)
5.0 3.141592653589793

Use as to give a different name, which is useful for long names or to avoid a clash:

from math import floor as fl, ceil
import statistics as stats

print(fl(2.7), ceil(2.1))
print(stats.mean([1, 2, 3, 4]))
2 3
2.5

A module can also live inside a package (a folder of modules, lesson 16.3), and the dots show the path:

import os.path
from os import path as p

print(os.path.join("a", "b").replace("\\", "/"))
print(p.basename("x/y.txt"))
a/b
y.txt

(The .replace only makes the output the same on Windows, whose own separator is a backslash.)

Which form to use?

Form Good for Watch out
import math most cases; the dot shows the origin slightly longer to write
import statistics as stats long module names; common conventions such as np for NumPy use well-known aliases only
from math import sqrt a few names used often the origin is not visible at the call
from math import * (almost) never see section 6

Put imports at the top of the file, one per line, in this order: standard library, then third-party, then your own modules (lesson 19.3).

4. Exploring a module

Two built-in tools let you look inside any module:

print([n for n in dir(math) if n.startswith("s")])
print(math.sqrt.__doc__[:40])
['sin', 'sinh', 'sqrt', 'sumprod']
Return the square root of x.
  • dir(module) lists the names in a module (the list printed here was cut to names starting with s).
  • help(module) or help(math.sqrt) shows the documentation in the terminal (try it; it is long).
  • The __doc__ attribute holds the documentation text.

The official documentation of the standard library at docs.python.org lists every module with examples; it is the best reference.

5. Import errors

Two things can go wrong with an import:

import nomodule
ModuleNotFoundError: No module named 'nomodule'

Python could not find a module with that name: a typo, a package that is not installed (lesson 16.6), or the file is not where Python looks (lesson 16.4). And:

from math import nothing
ImportError: cannot import name 'nothing' from 'math' (unknown location)

The module exists, but has no such name. ModuleNotFoundError is a kind of ImportError (lesson 14.2). A missing name accessed with a dot gives an ordinary AttributeError:

math.nothing
AttributeError: module 'math' has no attribute 'nothing'

(The "unknown location" in the message appears because math is built into this Python and has no file.)

6. Avoid import *

from math import * imports every public name into your file. It saves typing but causes trouble:

def sqrt(x):
    return "mine"

print(sqrt(4))
from math import *
print(sqrt(4))
mine
2.0

The second print shows that the star import silently replaced your own sqrt with the one from math. With *, readers cannot tell where a name came from, and a later version of the module may add a name that clashes with yours. Import what you need by name instead.

7. A module is loaded once

The first import of a module runs its code and stores the module object in sys.modules, a dictionary of loaded modules. Later imports, anywhere in the program, reuse that same object:

import sys

print("json" in sys.modules)
import json
print("json" in sys.modules, json is sys.modules["json"])

import math as m2
print(m2 is math)
False
True True
True

The first line is False only because json had not been imported yet in that run. Consequences:

  • Importing the same module many times is cheap.
  • Everything in a module is shared program-wide: changing a module's variable is visible to all importers.
  • Changing a module file while the program runs has no effect until you restart (or call importlib.reload, which is for special uses).

You can also import a module whose name is only known at run time:

import importlib

mm = importlib.import_module("math")
print(mm is math)
True

8. A tour of the standard library

You will meet many of these in chapter 17. A few for a taste:

Module Use
math, statistics, random numbers, summaries, chance
datetime dates and times
collections Counter, defaultdict, deque
pathlib, os, shutil files and folders
json, csv data files
re text patterns
argparse, logging command-line programs, logs

import this prints "The Zen of Python", a short poem of the language's design ideas. Try it.

Worked example: dice statistics

Roll a die 20 times (with a fixed seed, so the numbers are the same each run on this computer), summarise the rolls, and do a little geometry and date arithmetic. Each import style is used where it fits.

import math
import random
import statistics as stats
from collections import Counter
from datetime import date, timedelta

random.seed(42)
rolls = [random.randint(1, 6) for _ in range(20)]
print(rolls)
print("mean:", stats.mean(rolls), "median:", stats.median(rolls), "mode:", stats.mode(rolls))
print("stdev:", round(stats.stdev(rolls), 2))
print(Counter(rolls).most_common(2))

radius = 2.5
print(round(math.pi * radius ** 2, 2), math.ceil(radius), math.floor(radius))

start = date(2026, 3, 1)
print(start + timedelta(days=30), (date(2026, 12, 25) - start).days)
[6, 1, 1, 6, 3, 2, 2, 2, 6, 1, 6, 6, 5, 1, 5, 4, 1, 1, 1, 2]
mean: 3.1 median: 2.0 mode: 1
stdev: 2.13
[(1, 7), (6, 5)]
19.63 3 2
2026-03-31 299
Import Why this form
import math math.pi and math.ceil show where they come from
import statistics as stats a shorter name for a module used several times
from collections import Counter one class used on its own
from datetime import date, timedelta two names used on their own, as the library's own examples do

The seed makes the random numbers repeatable on a given Python version; another version could in principle produce different numbers. The dates are made up.

Common mistakes

  • Naming your own file like a standard module (random.py, math.py, json.py): Python imports yours instead of the real one, causing strange errors.
  • Using from x import *.
  • Forgetting the prefix after import math (sqrt(4) gives NameError).
  • Importing inside loops or functions without need.
  • Confusing the module name with a name inside it (import datetime versus from datetime import datetime).
  • Assuming a module is installed when it is a third-party package.

Key takeaways

  • A module is a Python file; the standard library has hundreds.
  • import x keeps names under x.; from x import y brings y in directly; as renames.
  • dir(module) and help(module) show what is inside.
  • ModuleNotFoundError means Python cannot find the module; ImportError for a missing name.
  • Avoid import *; a module is loaded once and shared.
  • Never give your own file the name of a standard module.

Practice

1. Import only ceil and floor from math.

Show answer

from math import ceil, floor

2. What is the difference between ModuleNotFoundError and ImportError: cannot import name?

Show answer

The first means no such module was found. The second means the module exists, but does not contain the name you asked for.

3. Why is from math import * discouraged?

Show answer

It hides where names come from and can silently replace your own names with the module's.

4. How do you list the names in the random module?

Show answer

dir(random) after import random (and help(random) for documentation).

5. If two files both import json, how many times does Python run the code of json?

Show answer

Once. The module object is stored in sys.modules and reused.

6. What can go wrong if you save a script as random.py and also import random?

Show answer

Python may import your own file instead of the standard module, so functions like random.randint are missing and you get confusing errors.