"Automate everything. […] Whether you use something as simple as shell scripts or full-featured solutions such as Ansible, Puppet, Chef, or Salt, just don’t rely on any manual intervention."

The Pragmatic Programmer , David Thomas & Andrew Hunt

Today I learned how to automatically enable %autoreload in your iPython session

The iPython REPL is great for quickly prototyping and debugging snippets of code.

Very often, you will import functions and classes from local scripts to use in your iPython session.

As you go through your debugging workflow, you might need to change or update the existing code in functions that you are importing into your iPython session.

By default, the iPython session does not automatically sync any new changes you make to external modules. Therefore, for the changes to pull through to your session you would need to exit the session and start a new one to load the changes.

This is pretty annoying default behaviour – I can’t think why you wouldn’t want to automatically sync changes in modules to your iPython session🤷‍♂️.

Using %autoreload

Thankfully, there is an iPython extension which allows you to autoreload any modules/functions imported into your session. Just add these two lines of code when you start the iPython session:

%load_ext autoreload
%autoreload 2

Great! We can now automatically sync changes from our local modules.

However, remembering to add these two lines of code every time you start a iPython session not convenient nor pragmatic . Especially when you forget!

Automate using the ipython config file

Luckily you can create an iPython configuration file to automatically run these lines of code every time you start a iPython session.

  1. Create an iPython configuration file in the following location: ~/.ipython/profile_default/ipython_config.py
  2. Add these lines to the config file:
    # ~/.ipython/profile_default/ipython_config.py
    c = get_config()
    c.InteractiveShellApp.exec_lines = []
    c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
    c.InteractiveShellApp.exec_lines.append('%autoreload 2')
    print("--------->>>>>>>> AUTORELOAD ENABLED <<<<<<<<<------------")

Next time you open your iPython session modules will autoreload automatically💪.

I added the print statement to the config to indicate that the configuration file has been applied to the session. Every time you start up the iPython REPL you will be greeted with the print statement to show that autoreloading is already enabled:

ipython config
Print statement showing autoreloading has been enabled when opening iPython session

You can access this configuration file setup from my dotfiles GitHub repo

That’s all today, happy coding!


Further Reading