Reloading Modules in a Python Interpreter

Sat, Oct 3, 2009

Tech Tips

If you have edited an external module (or .py file), you can reload the module from within the python interpreter by using the following command:

reload(myModule)

This assumes that you have imported the module at some point within your interpreter session.

When Is This Useful
It’s helpful if you are debugging code in a IDE like PyScripter. It’s quicker to test your programs within the IDE’s interpreter (it’s also the default). However if you have multiple files open and are making changes to them, your changes to files that have been imported already will not take affect. Unless you use the reload() command.

An Alternate Method
You can also programmatically remove the module from the cache. Then the next time your import is called, it will reload it:

if  'myModule' in sys.modules:
    del(sys.modules["myModule"])
import myModule
Bookmark and Share

3 Responses to “Reloading Modules in a Python Interpreter”

  1. jim.richmond Says:

    UPDATE:
    If you are using PyScripter, a better option is to enable the remote interpreter, this gives you the option of resetting the interpreter with a quick key press. It requires downloading the 2.6 version of the rpyc module. I placed it in my \Python\Lib\site-packages directory and restarted PyScripter. You can get additional info here: http://code.google.com/p/pyscripter/wiki/RemoteEngines

  2. Kumaresan Says:

    deleting loaded module from sys.module list and importing once again seems to be same as reload. so whats a big deal in reload(myModule)?

    • littlepig Says:

      The big deal with reload is that if module A depends on B and you change B, reload(A) will not reload the changes you’ve made on B, possibly causing strange behavior. The best thing is to delete from sys.module…