Importing Modules
Reuse code from other files and libraries with import.
Syntax
import module
from module import nameA module is a file of Python code you can reuse. Bring one in with import.
Import styles
import math— use asmath.sqrt(9).from math import sqrt— use assqrt(9).import numpy as np— import under a shorter alias.
Example
import random
from math import sqrt
print(sqrt(81))
print(random.randint(1, 6) <= 6)
# Output:
# 9.0
# TrueWhen 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.
import math
radius = 5
area = math.pi * math.pow(radius, 2)
print(f'Area: {area:.2f}') # Area: 78.54Import specific names
Imports only date and timedelta from datetime so they can be used without the module prefix.
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.
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