I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.
-
2It looks like this question was asked/answered prior to the release of reimport. See my answer below for new info. – kkurian Feb 03 '12 at 17:25
-
3Imports in Python are cached, so ordinarily the second and subsequent import gets the same code even if the file has changed. – Mark Ransom Jun 05 '15 at 17:10
11 Answers
Update for Python3: (quoted from the already-answered answer, since the last edit/comment here suggested a deprecated method)
In Python 3,
reload
was moved to theimp
module. In 3.4,imp
was deprecated in favor ofimportlib
, andreload
was added to the latter. When targeting 3 or later, either reference the appropriate module when callingreload
or import it.
Takeaway:
- Python3 >= 3.4:
importlib.reload(packagename)
- Python3 < 3.4:
imp.reload(packagename)
- Python2: continue below
Use the reload
builtin function:
https://docs.python.org/2/library/functions.html#reload
When
reload(module)
is executed:
- Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.
- As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.
- The names in the module namespace are updated to point to any new or changed objects.
- Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.
Example:
# Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py
# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py
# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2

- 141,215
- 6
- 77
- 149

- 21,871
- 18
- 78
- 106
-
16Note that reload only reloads the specified modules; that module's imports must be individually reloaded, too. – Richard Levasseur Mar 26 '09 at 01:28
-
I tried, but it did not work for me. In my case it's a Class File MyClass.py class MyClass: def __init__(self): return 1 def do_some_work(self): work = 2 + 3 print work – Mar 26 '09 at 01:37
-
7Also note that any objects that refer to anything in the module (like an instance whose class is defined in the module) will continue to use the old, pre-reload thing. In general, restarting the interpreter is the cleanest way to go. – Miles Mar 26 '09 at 01:38
-
1By the way, there is an interesting proposal addressing reload() issues at http://lists.canonical.org/pipermail/kragen-hacks/2002-January/000302.html – dragonfly Mar 26 '09 at 12:12
-
39Reload is now longer a function in [Python 3](http://docs.python.org/3.0/whatsnew/3.0.html#builtins). Use imp.reload() instead – Casebash Dec 12 '12 at 01:33
-
6`reload()` does not reliably reload packages or any modules imported by the top-level module. – Cerin Nov 12 '13 at 17:26
-
4Is there a similar way to use reload for statements such as: from src imort func as f ? – Evyatar Sivan May 22 '16 at 08:56
-
1
-
-
1Note that to use `importlib`, you must (ironically enough) first import it: `import importlib`. Then call `importlib.reload(packagename)`. – Gabriel Staples Oct 13 '18 at 21:29
-
If you're using the IDLE python interpreter, one can reload everything with a single press of F5. To do so, do not use the import statement. Instead, open your script from within IDLE from *File* > *Open*. Press F5 to load the script (practically does same thing as an *import* statement). After making your changes in an external editor and saving the changes, go back to the IDLE script window and press F5 again. Even though the IDLE script window doesn't show your changes, it all reloads properly in the interpreter itself. – Micah Lindstrom Apr 29 '20 at 03:21
-
This method might not override other modules' references to the reloaded module. See https://stackoverflow.com/a/61617169/2642356 for a solution to that. – EZLearner May 05 '20 at 15:58
-
this won't always look in the path again, so if the reason you are reloading is a sys.path change, this may not work – Erik Aronesty May 16 '22 at 18:22
All the answers above about reload()
or imp.reload()
are deprecated.
reload()
is no longer a builtin function in python 3 and imp.reload()
is marked deprecated (see help(imp)
).
It's better to use importlib.reload()
instead.

- 24,552
- 19
- 101
- 135

- 2,675
- 1
- 14
- 10
-
1Thank you. I do not see why this answer has no up votes. None of the other solutions works in Python 3.4. – wsaleem Aug 05 '14 at 07:12
-
5
-
This doesn't work for me. I get a message in the repl, saying that the module has no method liek that. – fraxture Jan 13 '16 at 09:57
-
20Problem is that you have to import `importlib` first. So after doing `import importlib`, you can then do `importlib.reload(some_module)`. – fraxture Jan 13 '16 at 09:59
-
4This works for me, but often not at first. My mistake is I keep forgetting that I had done something like "import bigfancything as bft" then try to do "importlib.reload(bigfancything)". You'd think a lazy person like me would try the shorter and correct "importlib.reload(bft)" first, but not so. – DarenW Apr 03 '17 at 20:37
-
Also a simple addition: If you want to reload changes in a sub module, "importlib.reload(module.submodule)" command can bu issued.. – ahmettolga Oct 12 '18 at 19:02
-
@fraxture, thank you! It seems like the library re-importation in python is basically garbage because of how frequently the rules are being changed, and how library re-importation is not recursive. There are probably fundamental reasons for why this is tricky, but I can't help but feel that it should not be so complicated. I mean, really, the code `import importlib`, then `importlib.reload(my_module)` is ridiculous. It shouldn't be that complicated. – Ryan Jensen Jan 20 '19 at 05:55
-
Actually, `importlib.reload` does not exist in Python2.7. Python3 is cute but not yet compatible with Python2.7. – personal_cloud Jul 26 '22 at 16:45
So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.
Yes, just saying import
again gives you the existing copy of the module from sys.modules
.
You can say reload(module)
to update sys.modules
and get a new copy of that single module, but if any other modules have a reference to the original module or any object from the original module, they will keep their old references and Very Confusing Things will happen.
So if you've got a module a
, which depends on module b
, and b
changes, you have to ‘reload b’ followed by ‘reload a’. If you've got two modules which depend on each other, which is extremely common when those modules are part of the same package, you can't reload them both: if you reload p.a
it'll get a reference to the old p.b
, and vice versa. The only way to do it is to unload them both at once by deleting their items from sys.modules
, before importing them again. This is icky and has some practical pitfalls to do with modules entries being None as a failed-relative-import marker.
And if you've got a module which passes references to its objects to system modules — for example it registers a codec, or adds a warnings handler — you're stuck; you can't reload the system module without confusing the rest of the Python environment.
In summary: for all but the simplest case of one self-contained module being loaded by one standalone script, reload()
is very tricky to get right; if, as you imply, you are using a ‘package’, you will probably be better off continuing to cycle the interpreter.
-
However, if you are talking about a test case and a changing unit test script, running reload on the sut should work just fine. In fact, I am wandering if adding "reload(sut module)" should be something I include as standard in the unit tests. – Danny Staple May 25 '11 at 10:05
In Python 3, the behaviour changes.
>>> import my_stuff
... do something with my_stuff, then later:
>>>> import imp
>>>> imp.reload(my_stuff)
and you get a brand new, reloaded my_stuff.

- 291
- 3
- 6
-
15And in Python 3.4, `imp` is deprecated in favor of `importlib`: `importlib.reload(my_stuff)`. – Aug 26 '14 at 07:34
No matter how many times you import a module, you'll get the same copy of the module from sys.modules
- which was loaded at first import mymodule
I am answering this late, as each of the above/previous answer has a bit of the answer, so I am attempting to sum it all up in a single answer.
Using built-in function:
For Python 2.x - Use the built-in reload(mymodule)
function.
For Python 3.x - Use the imp.reload(mymodule)
.
For Python 3.4 - In Python 3.4 imp
has been deprecated in favor of importlib
i.e. importlib.reload(mymodule)
Few caveats:
- It is generally not very useful to reload built-in or dynamically
loaded modules. Reloading
sys
,__main__
,builtins
and other key modules is not recommended. - In many cases extension modules are not
designed to be initialized more than once, and may fail in arbitrary
ways when reloaded. If a module imports objects from another module
using
from
...import
..., callingreload()
for the other module does not redefine the objects imported from it — one way around this is to re-execute thefrom
statement, another is to useimport
and qualified names (module.name) instead. - If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.
External packages:
reimport - Reimport currently supports Python 2.4 through 2.7.
xreload- This works by executing the module in a scratch namespace, and then patching classes, methods and functions in place. This avoids the need to patch instances. New objects are copied into the target namespace.
livecoding - Code reloading allows a running application to change its behaviour in response to changes in the Python scripts it uses. When the library detects a Python script has been modified, it reloads that script and replaces the objects it had previously made available for use with newly reloaded versions. As a tool, it allows a programmer to avoid interruption to their workflow and a corresponding loss of focus. It enables them to remain in a state of flow. Where previously they might have needed to restart the application in order to put changed code into effect, those changes can be applied immediately.

- 18,328
- 4
- 58
- 63
Short answer:
try using reimport: a full featured reload for Python.
Longer answer:
It looks like this question was asked/answered prior to the release of reimport, which bills itself as a "full featured reload for Python":
This module intends to be a full featured replacement for Python's reload function. It is targeted towards making a reload that works for Python plugins and extensions used by longer running applications.
Reimport currently supports Python 2.4 through 2.6.
By its very nature, this is not a completely solvable problem. The goal of this module is to make the most common sorts of updates work well. It also allows individual modules and package to assist in the process. A more detailed description of what happens is on the overview page.
Note: Although the reimport
explicitly supports Python 2.4 through 2.6, I've been trying it on 2.7 and it seems to work just fine.
-
1Excellent find. Seems to work well for simple cases in the interpreter when you make a small code change, and that's all I really wanted... – djs Oct 02 '12 at 05:51
Basically reload as in allyourcode's asnwer. But it won't change underlying the code of already instantiated object or referenced functions. Extending from his answer:
#Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py
# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
>>> x = mymodule.x
>>> x()
version 1
>>> x is mymodule.x
True
# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py
# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2
>>> x()
version 1
>>> x is mymodule.x
False

- 131,205
- 36
- 218
- 244
Not sure if this does all expected things, but you can do just like that:
>>> del mymodule
>>> import mymodule

- 1,590
- 10
- 14
import sys
del sys.modules['module_name']

- 22,111
- 8
- 69
- 76

- 141
- 2
- 4
-
1the `imp` and `importlib` solutions didn't work for me. This did. My situation was in a jupyter notebook where I needed to save a keras model, but had forgotten to run a `pip install h5py` beforehand. At the time of the saving, it threw an exception `save_model requires h5py`. Prepending this, and using the `save_model` imported from `keras.models` (instead of the `model.save(...)` function worked – Shadi Aug 11 '17 at 13:46
See here for a good explanation of how your dependent modules won't be reloaded and the effects that can have:
http://pyunit.sourceforge.net/notes/reloading.html
The way pyunit solved it was to track dependent modules by overriding __import__ then to delete each of them from sys.modules and re-import. They probably could've just reload'ed them, though.

- 1,442
- 14
- 9
-
Distilling this a bit - for me simple typing "reload(
)" works between tests. Simply using "del module; import module" will not work. – Danny Staple May 25 '11 at 10:02
dragonfly's answer worked for me (python 3.4.3).
import sys
del sys.modules['module_name']
Here is a lower level solution :
exec(open("MyClass.py").read(), globals())

- 4,074
- 22
- 28

- 413
- 4
- 10
-
That will not work exactly as requested, because the name space will change to global. Sorry. – Pierre ALBARÈDE Dec 18 '15 at 21:44