Sub topic 11
Reloading a module after you edit it
This chapter assumes you can start the shell, import modules, and read a traceback. It also assumes you know basic function and module syntax. Here you will learn why editing a file does not change an already imported module, how importlib.reload() fixes that, and where reloading stops working.
Why edits do not show up on their own
When you run import mymodule, Python does three things the first time it sees the name:
- It finds
mymodule.pyon disk. - It runs the file from top to bottom and builds a module object from the result.
- It stores that object in
sys.modules, a dictionary that maps module names to module objects.
On every later import mymodule, Python finds the name in sys.modules and returns the stored object. It does not read the file again. This cache is why importing the same module in ten places is cheap. In the shell, it also means that editing the file changes nothing in your running session.
Create a file named mymodule.py in the directory where you will start the shell:
# mymodule.py
def greet(name):
return "Hello, " + name
LIMIT = 3Start the shell from that directory and import it:
>>> import mymodule
>>> mymodule.greet("Ada")
'Hello, Ada'Now change greet in your editor so it returns "Hi, " + name, and save the file. Go back to the shell:
>>> import mymodule
>>> mymodule.greet("Ada")
'Hello, Ada'The second import did nothing. The module object in sys.modules still holds the old function.
Using importlib.reload()
The importlib module in the standard library provides reload(). It takes a module object, not a string:
>>> import importlib
>>> import mymodule
>>> # edit mymodule.py in your editor, then:
>>> importlib.reload(mymodule)
<module 'mymodule' from '/home/you/work/mymodule.py'>
>>> mymodule.greet("Ada")
'Hi, Ada'The shell echoes the module's repr because reload() returns the module. Assign the result or add a semicolon-free workaround such as _ = importlib.reload(mymodule) if the echo bothers you.
What reload does internally
reload() re-executes the module's source code in the existing module object's namespace. It does not create a new module object. Three consequences follow:
- Names defined in the new source are rebound.
greetnow points to the new function. - Names that existed before the edit but are no longer in the source are not removed. They stay in the module's namespace until you restart.
- Module-level code runs again. Any
print()call, file open, or global counter at the top of the file runs a second time.
You can see the second point directly. Add a name to the file:
# mymodule.py
def greet(name):
return "Hi, " + name
LIMIT = 3
OLD_FLAG = TrueThen reload, delete the OLD_FLAG line, and reload again:
>>> importlib.reload(mymodule)
<module 'mymodule' from '/home/you/work/mymodule.py'>
>>> mymodule.OLD_FLAG
True
>>> # delete the OLD_FLAG line in the editor, save, then:
>>> importlib.reload(mymodule)
<module 'mymodule' from '/home/you/work/mymodule.py'>
>>> mymodule.OLD_FLAG
TrueOLD_FLAG survives because reload only adds and overwrites names. If you suspect a stale name, check with dir(mymodule) or restart the shell.
The main gotcha: old references
reload() updates the module object, but any variable that already points to an old object keeps pointing to it. This is the most common reason for "I reloaded and it still behaves the old way."
from-imports
>>> from mymodule import greet
>>> # edit mymodule.py, then:
>>> importlib.reload(mymodule)
<module 'mymodule' from '/home/you/work/mymodule.py'>
>>> greet("Ada")
'Hello, Ada'
>>> mymodule.greet("Ada")
'Hi, Ada'The name greet in your session is a separate binding to the old function object. Reloading mymodule rebinds mymodule.greet but does not touch your session's greet. The fix is to import it again after reloading:
>>> from mymodule import greet
>>> greet("Ada")
'Hi, Ada'A habit that avoids the problem: while experimenting, use import mymodule and call mymodule.greet(...). The attribute lookup happens at call time, so it always finds the current function.
Existing instances
Objects created from a class keep a link to the class they were made from. If mymodule defines class Counter and you have c = mymodule.Counter(), then after a reload mymodule.Counter is a new class object. The variable c is still an instance of the old class and has the old methods. Create a new instance after each reload.
>>> c = mymodule.Counter()
>>> importlib.reload(mymodule)
<module 'mymodule' from '/home/you/work/mymodule.py'>
>>> isinstance(c, mymodule.Counter)
FalseThis False surprises people. It also breaks isinstance checks in your own code if some objects were built before a reload and some after.
Summary of what updates
| What you hold | After `reload(mymodule)` |
|---|---|
| `mymodule.func` looked up each time | Uses the new code |
| `from mymodule import func` done earlier | Still the old function |
| An instance made before the reload | Still tied to the old class |
| A name deleted from the source | Still present in the module |
| Module-level code | Runs again |
Modules that import other modules
reload() reloads only the module you pass it. It does not reload the modules that module imports.
Suppose app.py has import helpers, and you edit helpers.py. Running importlib.reload(app) re-executes app.py. Its import helpers line finds helpers in sys.modules and returns the cached copy, so your edit is ignored. You must reload the module you edited:
>>> importlib.reload(helpers)
<module 'helpers' from '/home/you/work/helpers.py'>
>>> importlib.reload(app)
<module 'app' from '/home/you/work/app.py'>The order matters. Reload the lower-level module first, then the modules that depend on it. If app.py uses from helpers import compute, reloading app after helpers makes app pick up the new compute. Reloading in the other order leaves app bound to the old function.
Errors during reload
A reload can fail, for example with a SyntaxError after a typo. Reading and compiling the file happens before the old namespace is touched, so a syntax error leaves the module as it was:
>>> importlib.reload(mymodule)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
File "/home/you/work/mymodule.py", line 2
def greet(name)
^
SyntaxError: expected ':'
>>> mymodule.greet("Ada")
'Hi, Ada'A runtime error is different. If the file compiles but raises an exception halfway through, names defined before the failing line are already rebound, and names after it are not. The module is then half old and half new. After any failed reload, fix the file and reload again before trusting the results.
Other ways to get a fresh module
Reloading is not the only option. Pick based on how much state you need to throw away.
| Approach | When to use it |
|---|---|
| `importlib.reload(mod)` | One module, small edits, session state you want to keep |
| `del sys.modules["mod"]` then `import mod` | You want a brand new module object with no leftover names |
| Restart the shell | Class hierarchies, many dependent modules, or any doubt about stale state |
| `python3 -i script.py` | You want a clean start each time, with the script's names loaded |
The del sys.modules approach gives a clean module object, but existing references still point to the old one:
>>> import sys
>>> del sys.modules["mymodule"]
>>> import mymoduleA practical loop
Putting it together, a reliable editing loop looks like this:
- Keep the shell open in one terminal and your editor in another.
- Use
import mymoduleand callmymodule.name(...). - After saving an edit, run
importlib.reload(mymodule). - Create fresh instances of any classes you are testing.
- If the behavior makes no sense, check
dir(mymodule)for stale names, or restart the shell.
You can press the up arrow to recall the importlib.reload(...) line, which makes the loop quick. This is covered in the chapter on line editing and history.
Once you reload more than a few times per session, or you need to test several modules together, the next chapter's advice applies: write the experiment into a file.
Exercise
You run from mymodule import greet, edit greet in mymodule.py, and call importlib.reload(mymodule). Calling greet("Ada") still gives the old result, but mymodule.greet("Ada") gives the new one. Why, and what are two ways to fix it?
Show answer
The name greet in your session is a separate binding to the old function object. Reload rebinds greet only inside mymodule. Fix it by running from mymodule import greet again after the reload, or by calling mymodule.greet(...) so the lookup happens at call time.
Exercise
app.py contains import helpers. You edit helpers.py and run importlib.reload(app). The edit has no effect. What should you run instead, and in what order?
Show answer
Reload helpers first with importlib.reload(helpers), then reload app with importlib.reload(app) if app holds names copied from helpers. reload(app) alone re-runs app.py, but its import helpers returns the cached module from sys.modules.
Exercise
You delete a constant OLD_FLAG from mymodule.py and reload. mymodule.OLD_FLAG still returns True. Why does this happen, and how can you get a module with no leftover names?
Show answer
Reload re-runs the source in the existing module's namespace. It adds and overwrites names but never removes old ones. To get a clean module, delete the entry with del sys.modules["mymodule"] and import it again, or restart the shell.