Re-importing a module

suggest change

When using the interactive interpreter, you might want to reload a module. This can be useful if you’re editing a module and want to import the newest version, or if you’ve monkey-patched an element of an existing module and want to revert your changes.

Note that you can’t just import the module again to revert:

import math
math.pi = 3
print(math.pi)    # 3
import math
print(math.pi)    # 3

This is because the interpreter registers every module you import. And when you try to reimport a module, the interpreter sees it in the register and does nothing. So the hard way to reimport is to use import after removing the corresponding item from the register:

print(math.pi)    # 3
import sys
if 'math' in sys.modules:  # Is the ``math`` module in the register?
    del sys.modules['math']  # If so, remove it.
import math
print(math.pi)    # 3.141592653589793

But there is more a straightforward and simple way.

Python 2

Use the reload function:

import math
math.pi = 3
print(math.pi)    # 3
reload(math)
print(math.pi)    # 3.141592653589793

Python 3

The reload function has moved to importlib:

import math
math.pi = 3
print(math.pi)    # 3
from importlib import reload
reload(math)
print(math.pi)    # 3.141592653589793

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents