Last updated: Apr 11, 2024
Reading time·3 min
To reload a module and its submodules in Jupyter Notebook:
%load_ext autoreload
magic command to enable automatic reloading.%autoreload 2
to specify that all modules should be reloaded before
executing the Python code.%load_ext autoreload %autoreload 2
Here is a complete example of a complete workflow.
%load_ext autoreload %autoreload 2 # Import your module from my_module import my_function my_function() # 100 # Open your IDE and update my_function to return 200 my_function() # 200
The autoreload
magic command reloads modules automatically before executing
your code.
All changed modules are reloaded before a new line is executed.
The module in the example above was reloaded and the function that was imported from the module was also updated.
The %autoreload 2
line reloads all modules every time before executing your
code.
You can print additional information about the %autoreload
magic command with
%autoreload?
.
%autoreload?
When you use the %autoreload
magic command:
from foo import bar
are
upgraded to new versions when foo
is reloaded.A.bar()
on an object A
created before the reload causes the new code for
bar()
to be executed.Some things to look out for when using this approach:
@property
in a class to a method or a method to a class
variable can cause issues.importlib.reload()
to reload a module in Jupyter NotebookYou can also use the importlib.reload() method to reload a module in Jupyter Notebook.
import my_module import importlib importlib.reload(my_module)
The importlib.reload()
method reloads a previously imported module.
The only argument the method takes is the module object you want to reload.
Note that the module must have been imported before passing it to the
importlib.reload()
method.
importlib.reload()
method also resets global variables that you've set in the module whereas the %autoreload
magic command doesn't.Using the importlib.reload()
method is useful if you have edited the module's
source code using an external code editor and want to try the new version
without having to restart Jupyter Notebook or the Python interpreter.
The importlib.reload()
method returns the module object.
import os import importlib module_obj = importlib.reload(os) # 👇️ <module 'os' from '/usr/lib/python3.10/os.py'> print(module_obj)
The module object might be different if re-importing causes a different object
to be placed in sys.modules
.
When the importlib.reload()
method is called:
You can learn more about the related topics by checking out the following tutorials:
pd.read_json()