Reading Time: 1 minutes
Reloading a Module in Python
Reloading a Module: There are occasions when you have changed the code of a module, and you want the changes to reflect without having to relaunch the interpreter or restart the server. Python doesn't support this by default. However, the reload() function of importlib standard library helps you to do just that.
Reloading a Module
# CONTENTS OF foo.py def spam(): print("SPAM!") # A SESSION IN THE INTERACTIVE INTERPRETER >>> import foo >>> foo.spam() SPAM! # CHANGED CONTENTS OF foo.py def spam(): print("SPAM! SPAM!") # SAME SESSION IN THE INTERACTIVE INTERPRETER >>> foo.spam() SPAM! # Changes have not reflected yet. >>> import importlib >>> importlib.reload(foo) <module 'foo' from 'complete_path_to_foo.py'> >>> foo.spam() SPAM! SPAM!
Common Practice to Handle Frequently Modified Modules
import moduleOne import moduleTwo from importlib import reload reload(moduleOne) reload(moduleTwo) from moduleOne import * from moduleTwo import *