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:


Importing modules:
* Re-importing a module

Table Of Contents
2 Filter
3 List
7 Loops
10 Importing modules
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve