How to reload my Python source file, when interactively interpreting it with "python -i"

This has to do with the way Python caches modules. You need a module object to pass to reload and you need to repeat the import command. Maybe there's a better way, but here's what I generally use: In Python 3:

>> from importlib import reload
>> import my_prog
>> from my_prog import *
*** Run some code and debug ***
>> reload(my_prog); from my_prog import *
*** Run some code and debug ***
>> reload(my_prog); from my_prog import *

In Python 2, reload is builtin, so you can just remove the first line.


When you use from my_prog import * you're pulling symbols into the interpreter's global scope, so reload() can't change those global symbols, only module-level attributes will be changed when the module is recompiled and reloaded.

For example: myprog.py:

x = 1

In interepreter:

>>> import myprog
>>> myprog.x
1
>>> from myprog import x
>>> x
1

Now edit myprog.py setting x = 2:

>>> reload(myprog)
>>> myprog.x
2
>>> x
1

Repeat the from myprog import * to pull the symbols to global scope again:

>>> reload(myprog)
>>> from myprog import *

Tags:

Python