A module is a Python file (.py) that contains functions, variables and classes ready to be used in other programs. Instead of writing everything from scratch, you import a module and take advantage of code that already exists. Python includes hundreds of modules out of the box: its famous "standard library".
import: bringing in a whole module
With import you load the module and access its contents by writing the module name, a dot and the name of what you want to use:
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
The module name works like a "surname" that tells you where each function comes from. That is why you cannot confuse math.sqrt with a function of your own called sqrt.
from … import: bringing in only what you need
If you are only going to use one or two things, you can import them directly and use them without the prefix:
from math import sqrt, pi
print(sqrt(16)) # 4.0
print(pi) # 3.141592653589793
as: giving it another name
With as you create an alias, useful for long names or to avoid name clashes:
import math as m
from math import sqrt as root
print(m.sqrt(25)) # 5.0
print(root(25)) # 5.0
Where to put the imports
By convention they are always placed at the top of the file, before the rest of the code, one per line:
import math
import random
radius = 3
print(math.pi * radius ** 2)
What is inside a module: dir and help
Two functions help you explore a module without leaving Python:
import math
print(dir(math)[:5]) # the first names the module contains
print(math.sqrt.__doc__) # help text of a function
help(math.sqrt) # full help on screen
dir(module)lists everything the module contains.help(module.function)shows what it is for and how to use it.
Common mistakes
ModuleNotFoundError. The module does not exist or is misspelled:
import maths
# ModuleNotFoundError: No module named 'maths'
NameError. Using the module without having imported it:
print(sqrt(16))
# NameError: name 'sqrt' is not defined
AttributeError. The module exists, but what you ask for is not in it:
import math
print(math.root(16))
# AttributeError: module 'math' has no attribute 'root'
Avoid from module import *. It brings in all the names at once, can overwrite your own variables and does not make it clear where each thing comes from.
Practice in Reusable functions.