When writing or debugging a Python program, I really like using the -i
command line switch to be able to directly inspect my functions without having to run everything from start to finish.
However, whenever I make a change to the code I have to close and restart my interactive session, losing all temporary variables that I might have defined. How do I reload my source file from within the python interpreter?
The builtin function reload
looks like it was made for this, but I can only use it with named modules:
>> import my_prog
>> print my_prog.x
-- prints an error, because x is not defined --
-- edited my_prog.py to add the x global now...
>> reload(my_prog)
>> print my_prog.x
-- prints x
However, if I instead to do a from my_prog import *
in the beginning reload doesn't work, and doing the import again also has no effect.
import importlib import inputs #import the module here, so that it can be reloaded. importlib. reload(inputs) from inputs import A # or whatever name you want. import inputs #import the module here, so that it can be reloaded.
The reload() is used to reload a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have made changes to the code.
On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With