refresing the edited python function

alex23 wuwei23 at gmail.com
Tue Aug 20 03:01:33 EDT 2013


On 19/08/2013 10:55 AM, Sudheer Joseph wrote:
> I have been using ipython and ipython with qtconsole and working on a
> code with functions. Each time I make a modification in function
> I have to quit IPTHON console (in both with and with out qt console )
> and reload the function freshly. If I need to see the changed I made in
> the function. I tried below options

> del function name
> import the module again  by issuing "from xxx.py import yy"

This doesn't re-import the module if xxx has already been imported. It 
simply rebinds xxx.yy to yy.

> import xxx.py

This also doesn't re-import the module if it has already been imported.

When you import a module, or a function from a module, a module object 
is created and stored in sys.modules. Any subsequent 'import <module>' 
calls will return a reference to that module object, and won't reload 
from file at all.

You can easily verify this by creating a test module 'foo' with a single 
line of `print('loading foo')` and then trying this from the console:

     In [1]: import foo
     loading foo

     In [2]: del foo

     In [3]: import foo

     In [4]:

Note that you only see 'loading foo' the first time you import the 
module. In order to have the module loaded again rather than returning 
the existing reference, you would use `reload(foo)`:

     In [5]: reload(foo)
     loading foo

So: in order to be able to use functions from a re-loaded module, you 
should always refer to them via the module object, and not import them 
directly:

     >>> import xxx
     >>> xxx.yy() # original code
     # ...modify function `yy` in your source file
     >>> reload(xxx)
     >>> xxx.yy() # new code

Or: you can reload the module and then rebind the functions:

     >>> from xxx import yy
     >>> yy() # original code
     # ...modify function `yy` in your source file
     >>> reload(xxx)
     >>> from xxx import yy
     >>> yy() # new code

Hope this helps.




More information about the Python-list mailing list