How to reload a module's function in Python?

Jonathan picture Jonathan · Sep 1, 2011 · Viewed 42.1k times · Source

Following up on this question regarding reloading a module, how do I reload a specific function from a changed module?

pseudo-code:

from foo import bar

if foo.py has changed:
    reload bar

Answer

Antony Hatchkins picture Antony Hatchkins · Oct 18, 2017

As of today, the proper way of doing this is:

import sys, importlib
importlib.reload(sys.modules['foo'])
from foo import bar

Tested on python 2.7, 3.5, 3.6.