How to reload a Python module

Reloading a Python module can be useful if you are doing interactive testing and development. For example, say you are making incremental changes to a function and with each change you want to poke at it in an interactive console. Or, perhaps you are working in a Jupyter notebook rather than an interactive console. Same idea.

In Python 3.4 and greater, do this:


import importlib
import my_great_module
importlib.reload(my_great_module)

In Python 3 prior to 3.4 do this:


import imp
import my_great_module
imp.reload(my_great_module)

In Python 2, do this:


import my_great_module
reload(my_great_module)

A word of caution from the importlib.reload documentation:

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains.

This effect can be demonstrated by calling dir() on a loaded module before and after removing some module variables and reloading the module.

Here are some useful references:

  1. http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module
  2. http://stackoverflow.com/questions/5516783/how-to-reload-python-module-imported-using-from-module-import
  3. https://docs.python.org/3.5/library/importlib.html#importlib.reload
Advertisements

One thought on “How to reload a Python module

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s