Clay Wardell
Clay Wardell

Reputation: 15602

Run code from a Python module, modify module, then run again without exiting interpeter

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?

Upvotes: 5

Views: 243

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

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.

Upvotes: 8

Related Questions