I'd like to be able to open a Python shell, execute some code defined in a module, then modify the module, then re-run it in the same shell without closing/reopening.
I've tried reimporting the functions/objects after modifying the script, and that doesn't work:
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from my_module import buggy_function, test_input
>>> buggy_function(test_input)
wrong_value # Returns incorrect result
# Go to the editor, make some changes to the code and save them
# Thought reimporting might get the new version
>>> from my_module import buggy_function, test_input
>>> buggy_function(test_input)
wrong_value # Returns the same incorrect result
Clearly reimporting did not get me the 'new version' of the function.
In this case, it isn't that big a deal to close the interpreter and reopen it. But, if the code I'm testing is complicated enough, sometimes I have to do a fair amount of importing objects and defining dummy variables to make a context that can adequately test the code. It does get annoying to have to do this every time I make a change.
Anyone know how to "refresh" the module code within the Python interpeter?
The reload() method is used to reload a module. The argument passed to the reload() must be a module object which is successfully imported before.
Take some lines of code, give them a name, and you've got a function (which can be reused). Take a collection of functions and package them as a file, and you've got a module (which can also be reused).
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
use imp.reload()
:
In [1]: import imp
In [2]: print imp.reload.__doc__
reload(module) -> module
Reload the module. The module must have been successfully imported before.
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