'self' disappearing

Daniel Nouri daniel.nouri at con-fuse.org
Fri Jul 4 18:19:29 CEST 2003


The idea of my simple piece of code is to start from a given module and 
wrap all functions and methods in that module and submodules. FunWrapper is 
the class that I use for wrapping.

The last two calls of main() in module bla are of interest. While the first 
'foo.bar(c)' works as expected, i.e. prints 'Hello from foo.bar' and 
'Calling bar', the second call bails out with:

  File "seque.py", line 9, in __call__
    self.fun(*args, **kwds)
TypeError: bar() takes exactly 1 argument (0 given)

It appears that 'instance.method()' is not the same as 
'klass.method(instance)' in this case. But why? And how do I deal with 
that?


---bla.py---

def a():
    print 'Hello from A'

def b():
    print 'Hello from B'

class foo:

    def bar(self):
        print 'Hello from foo.bar'

    def baz(self):
        print 'Hello from foo.baz'

def main():
    a()
    b()
    c = foo()
    foo.bar(c) #works
    c.bar() #raises TypeError (0 arguments given)

---seque.py---

import types

class FunWrapper:
    def __init__(self, fun):
        self.fun = fun

    def __call__(self, *args, **kwds):
        print 'Calling', self.fun.__name__
        self.fun(*args, **kwds)

def _traverse(object):
    for (name, obj) in object.__dict__.items():
        mytype = type(obj)

        if mytype in (types.FunctionType, types.UnboundMethodType):
            wrapper = FunWrapper(obj)
            object.__dict__[name] = wrapper

        elif mytype in (types.ModuleType, types.ClassType):
            _traverse(obj)


def seque(module, fun):
    _traverse(module)
    module.__dict__[fun]()


if __name__ == '__main__':
    import bla
    seque(bla, 'main')




More information about the Python-list mailing list