DEV Community

abbazs
abbazs

Posted on • Updated on

Automatic Code Reloading in IPython: How to Enable Autoreload at Startup

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:

  1. Press Win+R keys to open the run dialog.
  2. Type %USERPROFILE% and press Enter.
  3. Navigate to the .ipython folder. If the folder doesn't exist, these steps won't be applicable.
  4. Inside the .ipython folder, go to profile_default/startup.
  5. Create a file named 001.py.
  6. Open the 001.py file 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.")
Enter fullscreen mode Exit fullscreen mode
  1. Save the file and open IPython. The autoreload feature should now be enabled.

For Ubuntu:

  1. Open a terminal and navigate to ~/.ipython/profile_default/startup.
  2. Create a file named 001.py.
  3. Open the 001.py file and copy-paste the code mentioned in the Windows 10 instructions (Step 6).
  4. 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)

Collapse
 
gamepad_coder_6b4e822c025 profile image
Gamepad Coder • Edited

Thank you!
If you use .ipy instead of .py you can simply use the following instead:

#-------------------------------------------------
# .ipython/profile_default/startup/001-startup.ipy
#-------------------------------------------------
%load_ext autoreload
%autoreload 2
Enter fullscreen mode Exit fullscreen mode

References: