scoping/module life puzzle

Justin Shaw wyojustin at hotmail.com
Sun Dec 1 23:44:51 EST 2002


When you play with fire ...


> I would be grateful if someone can explain what's going on here. First
> off why do I need to keep a reference to the module (self._m=m) If I
> don't then it seems as though the module is dismembered (join-->None)
> even though the module object has an extant reference the run method.

All of the local variables inside A.run() will vanish when with function
returns.  This includes the local variable 'm'.  If you want to use it next
time around you need to save it somewhere besides the local name space (i.e.
as an attribute of self).  You could just as easliy assign directly to
self._m if you wished.

> Secondly even if I keep the module referenced why does A().run()(L)
> crash when a=A();a.run()(L) doesn't?

You are tossing the reference to object that contains run() and join gets
clobbered.  There are two fixes that you could do.
1. ' '.join(L) # use the space's join method (recommended)
2. stash a reference to self in the global name space:
def run(self):
    global saveme
    saveme = self
    ...

Odds are there is a better way to do what you are attempting.

Justin





More information about the Python-list mailing list