[Tutor] Is Python really dynamic ?

Michael P. Reilly arcege@shore.net
Sat, 24 Mar 2001 14:43:28 -0500 (EST)


> Moshe Zadka wrote:
> 
> > On Sat, 24 Mar 2001, Benoit Dupire <bdupire@seatech.fau.edu> wrote:
> >
> > > How can I force prog1.py to dynamically reload  module='func' ?
> >
> > Use reload()
> >
> 
> Thank you Moshe....II already tried reload() but it didn't seem to work..
> 
> >>> import prog1
> test
> 
> That works fine...!
> 
> Now change func.py, replacing
> 'setheading=SetHeading()'
> with 'toto=SetHeading()'
> 
> >>> reload(prog1)
> test
> <module 'prog1' from 'C:\Python20\prog1.pyc'>
> 
> Why does this still work ? setheading does not exist anymore....
> I had no clue... until i run this from the command line, where i got the correct
> results, and not from IDLE.
> 
> Could someone explain me why IDLE is messing everything up ?
> 
> Benoit
> 
> # func.py
> class SetHeading:
>     def run(self):
>         print 'test'
> stHeading=SetHeading()
> 
> # prog1.py
> class foo:
>     def __init__(self, module):
>         self.aa=__import__(module)
>         reload(self.aa)
>         chRef= getattr(self.aa, 'stHeading')
>         chRef.run()
> 
> my_foo = foo('func')

Actually it is because Python _is_ dynamic that you are having this
function.  Each module is independant, this includes when reloading
modules.  You will want to first reload func (accessible from
sys.modules), then reload prog1.  The reload function takes a module
object, not a module name.

But also Python _IS_ dynamic, you are only reloading a module, not
creating a new module and executing func.py from scratch.  This means
that the stHeading still exists with the same object is had.

>>> import proc1
test
>>> reload(proc1)
test
<module 'proc1'>
>>> # made your changes to func.py
...
>>> reload(sys.modules['func'])
<module 'func'>
>>> reload(proc1)
test
<module 'proc1'>
>>> dir(sys.modules['func'])
['SetHeading', '__builtins__', '__doc__', '__file__', '__name__', 'stHeading', 'toto']
>>>

Notice that we get both "stHeading" and "toto"?

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------