Importing Modules

Reuse code from other files and libraries with import.

Syntaximport module from module import name

A module is a file of Python code you can reuse. Bring one in with import.

Import styles

  • import math — use as math.sqrt(9).
  • from math import sqrt — use as sqrt(9).
  • import numpy as np — import under a shorter alias.

Example

Example · python
import random
from math import sqrt

print(sqrt(81))
print(random.randint(1, 6) <= 6)

# Output:
# 9.0
# True

When to use it

  • A script imports the 'os' module to build cross-platform file paths without hard-coding separators.
  • A developer imports only 'sqrt' from 'math' to avoid typing math.sqrt() throughout the file.
  • A team separates helper functions into a 'utils.py' module and imports them into the main app.

More examples

Import a module and use it

Imports the full math module and references its attributes with the 'math.' prefix.

Example · python
import math

radius = 5
area = math.pi * math.pow(radius, 2)
print(f'Area: {area:.2f}')   # Area: 78.54

Import specific names

Imports only date and timedelta from datetime so they can be used without the module prefix.

Example · python
from datetime import date, timedelta

today = date.today()
tomorrow = today + timedelta(days=1)
print(today, '->', tomorrow)

Import with an alias

Aliases 'os.path' as 'osp' for brevity when building file paths.

Example · python
import os.path as osp

home = osp.expanduser('~')
config = osp.join(home, '.config', 'app.ini')
print(config)
# e.g. /home/alice/.config/app.ini

Discussion

  • Be the first to comment on this lesson.