Python Quest

Track 10 · Lesson 1 of 12

Importing modules

Use import, from-import and aliases, understand what an import does, and explore a module with dir() and help().

About 30 minBeginner4 exercisesFree

You will be able to

  • Import a whole module and use its functions with dot notation
  • Import specific names with from-import and give modules or names an alias with as
  • Explain what Python does the first time a module is imported, and why a second import does nothing
  • Explore an unfamiliar module with dir(), help() and its attributes

Suppose a warehouse app needs the square root of a number, a rounded-up count of delivery boxes and the average of some ratings. You could write each of those yourself — or you could use code that already exists, has been tested by millions of people and ships with every copy of Python.

That code lives in modules. A module is a file of Python code (functions, constants, classes) that other programs can use. Python comes with a large collection of them called the standard library. To use one, you import it.

import module

The simplest form imports the whole module. You then reach inside it with a dot: module.name.

Importing the math module
import math

print(math.sqrt(81))
print(math.pi)
print(math.ceil(17 / 5))   # round UP: 3.4 becomes 4

Try it: Change math.ceil to math.floor and run it again. What changes?

import math creates one new name in your program: math. Everything the module provides stays inside it, so math.sqrt and math.pi say exactly where each name comes from. That is the main advantage of this form: a reader never has to guess where sqrt was defined.

from module import name

When you use one or two names a lot, you can copy them straight into your program:

Importing specific names
from math import sqrt, ceil

print(sqrt(144))
print(ceil(2.1))

Try it: Add a line print(math.pi). Why does it fail? Fix it by adding a separate import math line.

Now sqrt and ceil are names in your program, but math itself is not — from math import sqrt does not create the name math.

Aliases with as

as gives an imported module or name a different name in your program. Some aliases are so common they are a convention (import statistics as stats, and later import pandas as pd). Use aliases to shorten long names or to avoid a clash with a name you already use — not to invent cryptic abbreviations.

Aliasing a module and a function
import statistics as stats
from math import factorial as fact

ratings = [4, 5, 3, 5, 4]
print(stats.mean(ratings))
print(fact(5))

Try it: Try print(statistics.mean(ratings)). The alias is the only name that exists, so this raises NameError.

FormNames created in your programUse it as
import mathmathmath.sqrt(9)
import statistics as statsstatsstats.mean(xs)
from math import sqrtsqrtsqrt(9)
from math import factorial as factfactfact(5)
from math import *every public name in mathavoid: you can no longer tell where names come from

What an import actually does

The first time a program imports a module, Python:

  1. finds the module: first among the few modules compiled into Python itself (such as sys), then as a file in your program's folder, then in the standard library and installed packages;
  2. runs the module's code from top to bottom, creating its functions and variables;
  3. wraps the result in a module object and stores it in a cache called sys.modules;
  4. binds a name in your program to that object.

Every later import of the same module finds it in the cache and skips steps 1–3. The example below uses a small module file, greeting.py, that prints a line when its code runs. Watch how often that line appears.

A module's code runs only once, however many times it is imported
import greeting
import greeting
from greeting import welcome

print(welcome("Dana"))
print(greeting.WELCOME)

Try it: Add import sys and print('greeting' in sys.modules) at the end to see the cache.

Predict the output

import math as m

print(m.floor(7.8), m.ceil(7.2))
print(m.__name__)

Exploring a module: dir() and help()

A module is an object, and its contents are attributes. Two built-in functions let you look inside:

  • dir(module) returns a sorted list of the names the module defines. Names that start with an underscore are internal by convention.
  • help(thing) prints the documentation for a module or function — what it does and what arguments it takes.

Every module also has a few standard attributes, such as __name__ (its name) and __doc__ (its documentation string).

Looking inside a module
import math

names = [n for n in dir(math) if not n.startswith("_")]
print(len(names) > 40)
print(names[:6])
help(math.isqrt)

Try it: Replace math.isqrt with math.comb in the help() call and read what comb does.

Guided practice · ●difficulty 1 of 5 · about 4 min

Area of a round tablecloth

A textile shop sells round tablecloths. Write a function circle_area(radius) that returns the area of a circle (π × radius²) rounded to 2 decimal places.

Use math.pi from the math module — not a typed-in value like 3.14.

circle_area(1)     # 3.14
circle_area(2.5)   # 19.63
circle_area(10)    # 314.16

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Guided practice · ●●difficulty 2 of 5 · about 5 min

How many delivery boxes?

A courier packs items into boxes that each hold per_box items. A box that is only partly full still has to be sent. Write boxes_needed(items, per_box) that returns the number of boxes as an int.

Import ceil directly with from math import ceil and call it as ceil(...).

boxes_needed(10, 4)   # 3  (4 + 4 + 2)
boxes_needed(8, 4)    # 2
boxes_needed(0, 6)    # 0

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Challenge · ●●●difficulty 3 of 5 · about 7 min

List a module's names by prefix

When you explore a new module, you often want "every function whose name starts with is". Write public_names(module, prefix) that returns a sorted list of the module's attribute names that:

  • start with prefix, and
  • do not start with an underscore (those are internal).

Use dir() to get the names.

import math
public_names(math, "is")    # ['isclose', 'isfinite', 'isinf', 'isnan', 'isqrt']
public_names(math, "zzz")   # []

With an empty prefix, every public name is returned.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Debugging · ●●difficulty 2 of 5 · about 5 min

Fix the rating report

A café's feedback tool should summarise star ratings. rating_summary(ratings) must return a tuple (average, spread) where average is the mean rounded to 1 decimal place and spread is the square root of the population variance (the standard deviation) rounded to 2 places.

When the owner calls it, the program crashes with a NameError. Find and fix the import problems so it works:

rating_summary([4, 5, 3, 5, 3])   # (4.0, 0.89)

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Summary

  • import module creates one name; use module.name to reach inside it.
  • from module import name copies specific names into your program; as gives a module or name an alias.
  • The first import finds the file, runs its code once and caches the module object in sys.modules; later imports reuse it.
  • dir() lists a module's attributes and help() shows its documentation; underscore names are internal.