scoping/module life puzzle

Robin Becker robin at jessikat.fsnet.co.uk
Fri Nov 29 06:23:31 EST 2002


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.

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

######################
code='''from string import join
def run(L):
        print 'in run before join',
        X = join(L,' ')
        print 'in run after join',
        return X
'''
class A:
        def run(self):
                m = getattr(self,'_m',None)
                if not m:
                        from imp import new_module
                        m = new_module('myrunner')
                        exec code in m.__dict__
                        self._m = m #we must have this or nothing works
                return m.run

        def do_run(self,L):
                return self.run()(L)
L=['a','b','c']
a=A()
print 0,a.do_run(L)
print 1,a.run()(L)
print 2,A().do_run(L)
print 3,A().run()(L)
######################
output with self._m=m ie keep a ref to the module

C:\>\tmp\tmload.py
0 in run before join in run after join a b c
1 in run before join in run after join a b c
2 in run before join in run after join a b c
3 in run before join
Traceback (most recent call last):
  File "C:\tmp\tmload.py", line 25, in ?
    print 3,A().run()(L)
  File "<string>", line 4, in run
TypeError: 'NoneType' object is not callable
######################
If I comment self._m = m then nothing works 

C:\>\tmp\tmload.py
0 in run before join
Traceback (most recent call last):
  File "C:\tmp\tmload.py", line 22, in ?
    print 0,a.do_run(L)
  File "C:\tmp\tmload.py", line 19, in do_run
    return self.run()(L)
  File "<string>", line 4, in run
TypeError: 'NoneType' object is not callable

-- 
Robin Becker



More information about the Python-list mailing list