Sub topic 7
Importing and trying out modules
This chapter assumes you can start the shell and read its echoed results. It also assumes you know basic Python syntax. Here you will import modules into a session and try out their functions.
Why import in the shell
A module is a file of Python code that defines names such as functions and constants. The standard library ships hundreds of them. The shell is a quick place to test what a function returns before you put it in a program.
Three ways to import
The import statement binds a module to a name in your session.
>>> import math
>>> math.sqrt(16)
4.0
>>> math.pi
3.141592653589793You reach the module's contents with dot notation, module.name. Typing sqrt(16) alone raises NameError, because sqrt lives inside math, not in your session.
from ... import copies chosen names into your session, so you can skip the prefix.
>>> from math import pi, floor
>>> floor(pi)
3import ... as gives the module a shorter name.
>>> import statistics as stats
>>> stats.mean([2, 4, 9])
5| Form | Name you type | Best for |
|---|---|---|
| `import math` | `math.sqrt` | Exploring, since the module name shows where each name comes from |
| `from math import sqrt` | `sqrt` | Names you use repeatedly |
| `import statistics as stats` | `stats.mean` | Long module names |
Avoid from module import * in the shell. It dumps every public name into your session and can silently replace names you already defined.
What happens on import
Python looks for the module only once per session. The first import finds the file, runs its top-level code, and stores the resulting module object in a cache called sys.modules. Later imports of the same module reuse that object.
You can check the cache yourself.
>>> import sys
>>> 'math' in sys.modules
TrueThe cache has a consequence for experiments. If you edit a module's file and run import again, nothing changes, because Python reuses the cached copy. A later chapter covers reloading.
Trying your own module
When you start the shell with python3, the current directory is searched first. To try your own file, start the shell in the folder that holds it. Suppose greet.py contains this:
def hello(name):
return f"Hello, {name}!"Then, from the same folder:
>>> import greet
>>> greet.hello("Ada")
'Hello, Ada!'Leave off the .py extension. If you start the shell in a different folder, Python cannot see the file.
Common errors
ModuleNotFoundError means Python searched every location on sys.path and found no module of that name.
>>> import nosuchmodule
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'nosuchmodule'The usual causes are a typo, a third-party package that is not installed, or a shell started in the wrong folder.
ImportError on a from import means the module exists but lacks that name, for example from math import sqroot. Check the spelling against dir(math).
A shadowed module is a subtler problem. If your folder holds a file named random.py, import random loads your file instead of the standard library one. Strange AttributeError messages are the usual symptom. Print the module's __file__ attribute to see which file was loaded.
>>> import random
>>> random.__file__
'/usr/lib/python3.12/random.py'Your path will differ. If it points into your own project folder, rename your file.
Working habit
Import a module, then call its functions with small inputs and look at the echoed results. Use type() to confirm what comes back. Once an experiment works, copy the working lines into a file.
Exercise
You edit greet.py to change the greeting text, then run import greet again in the same session. The old greeting still appears. Why, and where does Python keep the old copy?
Show answer
The first import stored the module object in the sys.modules cache. A repeated import greet finds it there and does not re-read the file. The edit only takes effect after a reload (importlib.reload(greet)) or a fresh shell session.
Exercise
You run from math import sqroot and get an error. Which exception is it, and what can you check in the shell to find the right name?
Show answer
It is an ImportError, because the math module exists but has no sqroot name. Run import math and then dir(math) to list the available names. The correct one is sqrt.