Run the code from the Python module, change the module, then run again without leaving the interface

I would like to be able to open the Python shell, execute some code defined in the module, then modify the module and then re-run it in the same shell without closing / reopening.

I tried to rename functions / objects after changing the script, and this does not 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 

It is clear that re-import did not give me a “new version” of the function.

In this case, it is not a matter of closing the interpreter and reopening it. But if the code I'm testing is complex enough, sometimes I have to make quite a few importing objects and define dummy variables to create a context that can adequately test the code. It is annoying to have to do this every time I make a change.

Does anyone know how to “update” module code inside a Python interpreter?

+6
source share
1 answer

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. 
+9
source

All Articles