Post

\%load_ext autoreload and \%autoreload 2

Let's check the results immediately without restarting the kernel.

\%load_ext autoreload and \%autoreload 2

When developing code in Jupyter Notebook, it’s very inconvenient to restart the kernel every time you modify an external .py file. In this post, we’ll learn how to check the updated results immediately without restarting the kernel, even after modifying the module.

Usage

Enter the following in a cell at the top of your Jupyter Notebook:

1
2
%load_ext autoreload
%autoreload 2

Example

For example, let’s assume there is an external file named sample.py.

1
2
3
4
# sample.py

def hello():
    return "Hello World!"

Usage in the notebook:

1
2
3
from sample import hello

hello() # "Hello World!"

If you later modify sample.py as shown below:

1
2
3
4
# sample.py

def hello():
    return "Hello DS2Man!"

If you run the code below, the result from before the modification will appear.

1
2
3
from sample import hello

hello() # "Hello World!"

Even without restarting the kernel, if %autoreload 2 is set, you can immediately see the updated results when you run the next cell.

1
2
3
4
5
%load_ext autoreload
%autoreload 2
from sample import hello

hello() # "Hello DS2Man!"
This post is licensed under CC BY 4.0 by the author.