DEV Community

Cover image for Python Tip: Auto-reload the console on file changes
Loftie Ellis
Loftie Ellis

Posted on • Originally published at loftie.com

Python Tip: Auto-reload the console on file changes

I find myself using the python console often in python (and Django) to test various things. But one annoying thing was that I had to restart the console (and all imports/commands until the line) every time I made the change.

There is a better way though.

IPython autoreload

If you use IPython as your console, you can use the autoreload extension to automatically reload code up the current state. This makes the following flow possible:

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from foo import some_function

In [4]: some_function()
Out[4]: 42

In [5]: # open foo.py in an editor and change some_function to return 43

In [6]: some_function()
Out[6]: 43
Enter fullscreen mode Exit fullscreen mode

See https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html for more information.

Usage in PyCharm

PyCharm does not yet fully support the IPython config, but you can still set it up without too much work.

First, make sure you have IPython installed:

pip install ipython

  • *Then, in Settings->Build,Execution,Deployment->Console make sure you have 'Use IPython if available' checked.

Last step is to add the following two lines to the Starting script.

%load_ext autoreload
%autoreload 2
Enter fullscreen mode Exit fullscreen mode

Console settings in PyCharm

That's it, now your console will automatically reload whenever you make file changes.

Also check out my other article for how to automatically load your models in the Django console.

Top comments (1)

Collapse
 
tech2blog profile image
Tech2Blog.com

Very useful tip @lpellis . Keep sharing your knowledge.