liveBook · Manning

Reload

As explained in The Quick Python Book, Fourth Edition

reload is a Python operation that re-executes a previously imported module's code in an existing interpreter session.

Use reload when you edit an imported Python module and want to test the new version in the same interpreter session. Repeating import does not load the changed file: Python tracks modules it has already loaded. section 10.2

Test an edited module

After changing mymath.py on disk, run: import mymath, importlib importlib.reload(mymath) The call returns the mymath module. You can then call its functions to test the changes. section 10.2

Reloading parses the module code again, so a syntax error raises an exception. It is not quite equivalent to starting a fresh interpreter and importing the module for the first time. If you need a clean session, restart the interpreter instead; in Colaboratory, use Runtime → Restart Session. section 10.2

A fix that still appears broken

Suppose a text-processing module fails because it uses string.punctuation without importing string. Adding import string to the module file is only the first step: the old version remains loaded in the current session. Run importlib.reload(text_processing), or restart the session, before retrying. section 10.8.2

An earlier example uses imp.reload(wo) for the same edit-and-test task. The importlib example uses importlib.reload(mymath). section 3.5 section 10.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains why repeated import fails, gives reload syntax and a fresh-session caveat, but defers the detailed differences to the Python reference.
Examples
Uses mymath.py for the basic call and a missing string import for a debugging case.
What it assumes
Assumes familiarity with Python modules and import statements, while explaining why another import does not load disk changes.
What you can do after
Apply it via importlib.reload to test an edited module in the current session, or restart when a clean session is needed.
How it connects
Connects reload to module imports, interpreter sessions, syntax errors, and Python bytecode.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.