Python Glossary Русский

Python 3.4+importlibfunction

importlib.reload()

reloading and caches

Re-executes the code of an already imported module and updates its object in place; useful in a REPL or Jupyter after editing the file.

Syntax

module = importlib.reload(module)

Only the module object itself is updated: names taken with from m import x still point to the old values, and instances of old classes stay instances of the old classes, so isinstance against the new class is False. The argument is a module, not a string: reload('m') raises TypeError. Names deleted from the file do not disappear from the module — reload does not clear its dictionary.

Examples

import importlib, sys
sys.path.insert(0, '.')
with open('cfg.py', 'w') as f:
    f.write('VALUE = 1\n')
import cfg
from cfg import VALUE
with open('cfg.py', 'w') as f:
    f.write('VALUE = 200  # changed\n')
importlib.reload(cfg)
print(cfg.VALUE, VALUE)  # → 200 1 — from-импорт остался старым
try:
    importlib.reload('cfg')
except TypeError as e:
    print(e)  # → reload() argument must be a module

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy