Importing Modules

Concepts covered: Iteration

Python ships with hundreds of modules, each a file of code written and tested for you: square roots, random numbers, dates, text in JSON form. Python loads a module only when you ask for it. The import statement finds the module's file, runs it once, and binds the module's name in your program so you can reach what it holds with a dot.

import math

print(math.sqrt(144))
print(math.pi)
print(math.floor(7.8))

Output:

12.0
3.141592653589793
7

Read math.sqrt as the sqrt that lives inside math. After line 1 the name math refers to the module, and the dot looks inside it for a name. sqrt returns a float even for a perfect square, pi is a plain float with 15 digits after the point, and floor drops the fraction and hands back an int. Leave out line 1 and the name math means nothing to the program.

print(math.sqrt(144))

The program stops on its first line with a NameError, the same error a misspelled variable produces. The module exists on disk, but nothing in this program has named it yet. Section 3 reads traceback lines in full; for now, a NameError on a module's name means a missing import.

2 ways to import

import math brings in the whole module under one name, and every use carries the prefix. from math import sqrt, pi copies those 2 names into your program, so you call sqrt(81) with no prefix. The second form reads shorter, at the cost of hiding where sqrt came from when someone reads line 40 of your file.

from math import sqrt, pi

print(sqrt(81) * pi)

Output:

28.274333882308138
import math
  • One name is added to your program: math
  • Every use carries the prefix: math.sqrt(2)
  • The origin of each name is visible at the call
  • Safe when 2 modules both define a sqrt
from math import sqrt
  • The name sqrt is added directly
  • Calls read shorter: sqrt(2)
  • A reader scrolls to the top to find the origin
  • A later from cmath import sqrt silently replaces it

Which line fails when this program runs, and with what error?

from math import sqrt

print(sqrt(16))
print(math.floor(2.7))

A tour of the standard library

ModuleWhat it holdsOne name inside
mathsquare roots, rounding, constantsmath.sqrt(x)
randomrandom numbers and random choicesrandom.randint(1, 6)
datetimedates, times and the gaps between themdatetime.date.today()
jsonturning JSON text into Python values and backjson.loads(text)
osthe operating system: paths, folders, environmentos.getcwd()
timepausing, and measuring elapsed secondstime.sleep(2)

Each of these is installed with Python itself, so import json works on any machine that has Python and nothing else. Naming a module that does not exist, or misspelling one, fails at the import line with a ModuleNotFoundError rather than somewhere later in the program.

import maths

Importing your own file

A module is any file ending in .py, including the ones you write. Save the constants and helpers that 2 scripts share in a file named pricing.py, and both scripts can import pricing. The module's name is the filename without .py, and Python looks for it first in the folder the running script lives in.

TAX_RATE = 0.08

def with_tax(price):
    return price * (1 + TAX_RATE)
import pricing

print(pricing.TAX_RATE)
print(pricing.with_tax(100))

Importing pricing runs every line of pricing.py once, top to bottom, which is how TAX_RATE gets its value and with_tax gets defined. A print at the top level of pricing.py would run at import time too, which surprises people the first time a bare import produces output. Keep a module's top level to constants and definitions, and the importing script decides what gets printed.

Practice

About this lesson

This section is part of the Python Foundations: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.