Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
Clay Wardell Avatar asked Jan 24 '13 00:01

Clay Wardell


People also ask

How do you reload a Python module?

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.

How do you reuse the functions defined in a module in your program?

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).

What does __ init __ PY do in Python?

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.


1 Answers

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.
like image 182
Ashwini Chaudhary Avatar answered Sep 23 '22 21:09

Ashwini Chaudhary