reload

Johannes Stezenbach yawyi at gmx.de
Thu Mar 16 13:44:27 EST 2000


Jerome Chan <eviltofu at rocketmail.com> wrote:
>What would happen if a module tried reloading itself?
>
>if check_updates(address):
>   get_updates(address)
>   reload(this_module)

Before a module can reload itself, it must import itself (to associate
"this_module" with a reference to the module object in the current
namespace), or you must refer to sys.modules["this_module"].

>where would the execution flow proceed after that? I'm trying to make a 
>self updating library...

The code object which contains the code of the current function/method
is unaffected by the reload(), so the old code will be in effect until
the current function/method returns. OTOH, since name lookups are
dynamic in python, every function call after the reload() will
find the new code.

BUT: This will not work for method calls, because class instances
have a reference to the old class object, which in turn has
references to the old methods' code objects, i.e. the old code
will stay alive as long as there are instances alive that reference
it. New instances will use the reloaded code, though.
If you need dynamic reload of classes to have an effect on
exisiting instances, you will either have to patch the reference to
the new (reloaded) class into the existing instances (set the
__class__ attribute of the instance), or patch the  new methods into the
old class object (modify the __dict__ attribute of the class object).
It's not easy, but possible.

Johannes




More information about the Python-list mailing list