Automatic Code Reloading in IPython: How to Enable Autoreload at Startup
The autoreload extension in IPython provides a convenient way to automatically reload modules before executing code. This feature is especially useful during development when code changes need to be reflected in the IPython session without the need for manual reloading. In this cheatsheet, we'll walk through the steps to enable autoreload at startup in both Windows 10 and Ubuntu.
Setting Autoreload at Startup
To enable autoreload at startup, follow the instructions below for both Windows 10 and Ubuntu.
For Windows 10:
- Press
Win+Rkeys to open the run dialog. - Type
%USERPROFILE%and press Enter. - Navigate to the
.ipythonfolder. If the folder doesn't exist, these steps won't be applicable. - Inside the
.ipythonfolder, go toprofile_default/startup. - Create a file named
001.py. - Open the
001.pyfile and copy-paste the following code:
import IPython
ipython = IPython.get_ipython()
if ipython is not None:
ipython_version = IPython.__version__
major_version = int(ipython_version.split('.')[0])
minor_version = int(ipython_version.split('.')[1])
if major_version < 8 or (major_version == 8 and minor_version < 1):
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")
else:
ipython.run_line_magic(magic_name="load_ext", line="autoreload")
ipython.run_line_magic(magic_name="autoreload", line="2")
print("Autoreload enabled.")
else:
print("Autoreload not enabled.")
- Save the file and open IPython. The autoreload feature should now be enabled.
For Ubuntu:
- Open a terminal and navigate to
~/.ipython/profile_default/startup. - Create a file named
001.py. - Open the
001.pyfile and copy-paste the code mentioned in the Windows 10 instructions (Step 6). - Save the file and open IPython. The autoreload feature should now be enabled.
By following these steps, you can automatically enable the autoreload extension in IPython, allowing code changes to be automatically reflected in your IPython session without the need for manual reloading.
Top comments (1)
Thank you!
If you use
.ipyinstead of.pyyou can simply use the following instead:References: