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 and what a module is: a file of Python code, or a built-in library, that you load by name. Here you will learn what import does inside a live session, how to try a module's functions quickly, and which errors and surprises to expect.
What an import does in a session
The standard library ships with Python, and the shell is the fastest way to test one of its functions before you put it in a program. An import statement does two things:
- It finds the module and runs its code, but only if the module has not been loaded already.
- It binds a name in your session to the module object.
>>> import math
>>> math.sqrt(16)
4.0
>>> math.pi
3.141592653589793
>>> math
<module 'math' (built-in)>Typing the module name echoes its repr, which tells you what you hold. Some modules show a file path instead of (built-in), and the path depends on your installation.
An import runs code, and that code can have visible effects. The classic example is import this, which prints the "Zen of Python" when the module loads.
Choosing an import form
The form you choose decides which names land in your session.
| Statement | Name bound in your session | Use afterwards |
|---|---|---|
| `import math` | `math` | `math.sqrt(9)` |
| `import math as m` | `m` | `m.sqrt(9)` |
| `from math import sqrt` | `sqrt` | `sqrt(9)` |
| `from math import sqrt as root` | `root` | `root(9)` |
| `from math import *` | every public name in the module | `sqrt(9)` |
For experiments, import module keeps the origin of every name visible, which helps when you paste working lines into a file later. from module import name saves typing when you call one function many times:
>>> from collections import Counter
>>> Counter("banana")
Counter({'a': 3, 'n': 2, 'b': 1})
>>> from fractions import Fraction
>>> Fraction(1, 3) + Fraction(1, 6)
Fraction(1, 2)Avoid from module import * in the shell. It can silently replace names you defined earlier, and you can no longer tell which module a function came from.
A from import binds your name to the object at that moment. If the module later rebinds its own variable, your name still points to the old object. For this reason, use module.name for values that might change, and use from mostly for functions and classes.
Imports run once
Python keeps every loaded module in a dictionary called sys.modules. A second import of the same name finds the module there, skips the file, and only binds the name again.
>>> import sys
>>> import math
>>> sys.modules['math'] is math
TrueYou can see the effect with a small module of your own. Create greet.py in the directory where you start the shell:
print("loading greet")
def hello(name):
return f"Hello, {name}"Then try it:
>>> import greet
loading greet
>>> import greet
>>> greet.hello("Ada")
'Hello, Ada'The print call at the top of the module ran only once. This explains a common confusion. If you edit greet.py and run import greet again, nothing changes, because Python reuses the cached module. A later chapter covers importlib.reload(), which fixes this.
Where Python looks for modules
When a module is not in sys.modules, Python searches the directories in sys.path in order. Built-in modules and the standard library are found through this search too. In an interactive session, the first entry of sys.path is an empty string, which means "the current working directory".
That placeholder is not the diagram. Here is the actual diagram:
Because the current directory is searched first, your own files take priority over the standard library. This leads to the most confusing import bug.
Shadowing a standard module
Suppose you save a scratch file called statistics.py in your working directory and start the shell there.
echo 'print("this is my file")' > statistics.py
python3>>> import statistics
this is my file
>>> statistics.mean([1, 2, 3, 4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'statistics' has no attribute 'mean'Your file replaced the real module. Check statistics.__file__ to see which file was loaded. If it points into your project directory instead of the Python installation, rename your file and delete any __pycache__ folder it created. Then restart the shell. Choose scratch file names that no library uses, such as try_stats.py.
Import errors you will see
Two exceptions cover most import failures. Both leave your session intact.
ModuleNotFoundError means Python could not find the module at all:
>>> import numpyy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpyy'Typos are one cause. The other is a module that is not installed in the Python you are running. A common situation on machines with several Pythons is that pip installed a package for one interpreter while your shell runs another. Ask the shell which interpreter it is:
>>> import sys
>>> sys.executable
'/usr/bin/python3'Your path will differ. To install into exactly that interpreter, run python3 -m pip install package_name from the terminal, using the same command you use to start the shell.
ImportError is raised when the module exists but the name you asked for does not:
>>> from collections import Countr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'Countr' from 'collections' (...)The text in the parentheses is the module's file path, which differs between installations. ModuleNotFoundError is a subclass of ImportError, so except ImportError catches both.
Submodules and packages
A package is a module that contains other modules. Importing the package does not always import its submodules, so an attribute can be missing even though the code exists:
>>> import xml
>>> xml.dom
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'xml' has no attribute 'dom'
>>> import xml.dom
>>> xml.dom.__name__
'xml.dom'After import xml.dom, the name xml is bound to the top-level package, and dom is reachable as an attribute of it. Some packages import their own submodules, so this error appears for some packages and not others. When an attribute is missing, import the dotted name explicitly.
Overwriting a module name by accident
The shell shares one namespace for modules and your own variables. A natural variable name can destroy a module reference:
>>> import random
>>> random = random.random()
>>> random.choice([1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'choice'The name random now refers to a float. The module is still in sys.modules, so running import random again rebinds the name without reloading anything. Prefer descriptive variable names such as roll, and avoid names like random, json, time, or sum for values.
A short exploration routine
When you meet an unfamiliar module, this sequence works well. It uses tools from the introspection chapter, so only a quick summary is given here.
- Import it with
import module. - Run
dir(module)to see its names, andhelp(module.name)to read the documentation for one of them. - Call a function with a small input you can verify by hand.
- Check the type of the result with
type(...).
>>> import statistics
>>> statistics.mean([1, 2, 3, 4])
2.5
>>> type(statistics.mean([1, 2, 3, 4]))
<class 'float'>
>>> statistics.median([3, 1, 2])
2(This session assumes you are not in the directory containing the shadowing statistics.py from earlier.)
Testing with inputs whose answer you already know catches wrong assumptions early, such as a function that returns a float where you expected an integer.
Summary of rules
import namebinds one name and runs the module only on first use.sys.modulescaches loaded modules, so repeated imports are cheap and do not pick up edits.sys.pathis searched in order, and the current directory comes first in the shell.ModuleNotFoundErrormeans the module is missing or the wrong interpreter is running.ImportErrorcan mean the module is present but lacks the name you asked for.- Reassigning a module's name to another value breaks it until you import it again.
Exercise
You create json.py in your working directory for an experiment. In a new shell, import json succeeds, but json.dumps({"a": 1}) raises AttributeError. Explain why, and name two ways to confirm and fix the problem.
Show answer
The current directory is first on sys.path in an interactive session, so import json loaded your file instead of the standard library module, and your file has no dumps. Confirm it by printing json.__file__, which will point to your directory, or by checking that sys.path[0] is an empty string. Fix it by renaming json.py to something unique, deleting the __pycache__ folder if one was created, and starting a new shell.
Exercise
A module file tools.py contains print("loaded") and a function run(). In one session you run import tools, edit the file so run() returns a different value, and run import tools again. What does the second import print, which version of run() do you get, and why?
Show answer
The second import prints nothing and run() is still the old version. The first import stored the module in sys.modules, and the second import found it there, so Python did not read the file again. To see your edit you must reload the module with importlib.reload(tools) or start a new shell.