Importing Modules
Exit

Importing Modules

Use import, from...import, and aliases to bring code into your file

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Three ways to import

Python gives you three import styles. Each has a trade-off between clarity and convenience.

1. Import the whole module

import math

print(math.sqrt(16))  # 4.0

You access functions with the module.function() syntax. This is the clearest style — every call shows where the function comes from. When you read math.sqrt(), you know instantly it belongs to the math module.

2. Import specific names

from math import sqrt, ceil

print(sqrt(16))   # 4.0
print(ceil(3.2))  # 4

This pulls specific functions directly into your namespace. You call sqrt() instead of math.sqrt(). The code is shorter, but you lose the visual reminder of where the function lives.

Use this style when you call a function many times and the module name is obvious from context.

3. Import with an alias

import math as m

print(m.sqrt(16))  # 4.0

An alias gives the module a shorter name. This is common with long module names. The data science community standardized on aliases like import numpy as np and import pandas as pd — you will see these everywhere.

Combining styles

You can mix import styles in one file. A common pattern imports the module for general use and pulls out one heavily-used function:

import os
from os.path import join

full_path = join("data", "report.csv")

What not to do

Avoid from math import *. The star imports every name from the module into your namespace. If two modules define a function with the same name, the second import silently overwrites the first. Your code breaks with no warning.

from math import *     # Imports everything — don't do this
from statistics import *  # May overwrite names from math

Explicit imports make your code predictable.

Instructions

Practice the three import styles.

  1. Import the math module. Use the plain import statement.
  2. Call print() with math.sqrt(25).
  3. Import ceil and floor from the math module. Use the from ... import style.
  4. Call print() with ceil(3.2).
  5. Call print() with floor(3.8).
  6. Import the math module with the alias m. Use import ... as.
  7. Call print() with m.pow(2, 10).