Modules and imports¶
~15 min ยท prerequisite: Recursion basics
What you will be able to do¶
- Import a module from Python's standard library with
import, and use its functions. - Import a single name with
from ... import, and rename an import withas. - Split code into your own module file, and import it from another file.
The idea¶
A module is a file that holds Python code, such as functions and values. Its file name ends in .py, and its name is the file name without that ending. Keeping related code in a module lets you reuse it in other programs without copying it.
Python ships with many modules already installed. These are the standard library. One example is math, which holds functions such as sqrt for square roots, and values such as pi. To use a module, you write import followed by its name. The names inside the module are then reached with a dot, such as math.sqrt. The dot means "the name sqrt that belongs to math".
Think of a module as a toolbox. You open the box with import, and then reach for the tool you need, using its label. Each module has its own names, so math.sqrt and a function of your own called sqrt do not clash.
You can also import one name directly with from math import sqrt. Then you write sqrt(16) without the module name. You can rename an import with as, as in import math as m, and then write m.sqrt. Both forms are valid. The dotted form is used in most of this course, because the module name shows where each function comes from.
When Python runs an import line for a module it has not loaded yet, it runs that module's code once, and keeps the result. Later imports of the same module reuse it.
To write your own module, save functions in a file, such as greetings.py. Another file in the same folder can then run from greetings import hello. When you run a file directly, Python sets the special name __name__ to "__main__". When the same file is imported, __name__ holds the module's name instead. This lets a file hold a demo under if __name__ == "__main__":, which runs only when you run that file itself.
Worked example¶
Expected output:
Line by line, this is what Python does:
import mathloads the standard library module namedmath, and binds the namemathto it.math.sqrt(16)calls the functionsqrtthat belongs tomath. The result is the float4.0, becausesqrtalways returns a float.printshows4.0on the first line.math.pi > 3.14compares the constantpiwith3.14. The comparison isTrue, andprintshows it.
Try it¶
The first block uses three functions from math. The second block imports one name and renames it. The third block combines an import with a function of your own.
Two files work together like this. Save the first as greetings.py, and the second as main.py, in the same folder.
# greetings.py
def hello(name):
return "Hello, " + name
if __name__ == "__main__":
print(hello("module demo"))
Running python3 main.py in that folder prints Hello, Ada. Running python3 greetings.py prints Hello, module demo. The second message appears only when the file runs directly.
Common mistakes¶
-
Misspelling a module name. The following line has an extra letter:
Python reports:
Check the spelling. The standard library module is
math. -
Using a function without importing it. The following line calls
sqrtwithout writingmath.in front:Python reports:
Write
math.sqrt(16), or import the name withfrom math import sqrt. -
Calling a name that is not in the module. The following line uses a function that
mathdoes not have:Python reports:
Check the spelling in the documentation. Multiplying
3 * 3also gives the square. -
Calling a module as if it were a function. The following line puts parentheses after the module name:
Python reports:
Call a function inside the module instead, such as
math.sqrt(4).
Practice¶
- Use
math.sqrtto show thatmath.sqrt(81)equals9.0. Write anassertfor it. - Use
from math import pi, and assert thatround(pi, 2)equals3.14. - Define
hypotenuse(a, b)usingimport math as m, and returnm.sqrt(a * a + b * b). Assert thathypotenuse(3, 4)equals5.0. - Define
lcm(a, b)that returns the least common multiple, usingfrom math import gcdand the formulaa * b // gcd(a, b). Assert thatlcm(4, 6)equals12and thatlcm(7, 3)equals21. - Stretch: use
from math import comb. Definecount_routes(rows, cols)that returnscomb(rows + cols - 2, rows - 1), the number of paths that go right or down across a grid. Assert thatcount_routes(2, 2)equals2, and thatcount_routes(3, 3)equals6.
Solution
- ```python import math
assert math.sqrt(81) == 9.0 ```
- ```python from math import pi
assert round(pi, 2) == 3.14 ```
- ```python import math as m
def hypotenuse(a, b): return m.sqrt(a * a + b * b)
assert hypotenuse(3, 4) == 5.0 ```
- ```python from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
assert lcm(4, 6) == 12 assert lcm(7, 3) == 21 ```
- ```python from math import comb
def count_routes(rows, cols): return comb(rows + cols - 2, rows - 1)
assert count_routes(2, 2) == 2 assert count_routes(3, 3) == 6 ```
Recap¶
import mathgives you the module, and you reach its names with a dot, such asmath.sqrt.from module import namebrings in one name, andasgives an import a new name.- Your own module is a
.pyfile. Useif __name__ == "__main__":for code that should run only when that file is run directly.