Welcome, guest | Sign In | My Account | Store | Cart

A class whose objects can handle undefined method calls, passing them on to a default handler.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class C:
    def handlerFunctionClosure(self,name):
        def handlerFunction(*args,**kwargs):
            print name,args,kwargs    # do what you want to here
        return handlerFunction
    def __getattr__(self,name):
        return self.handlerFunctionClosure(name)

# Use as follows
# >>> c = C()
# >>> c.foo(1,color="blue")
#foo (1,) {'color': 'blue'}

The only remotely tricky part here is that the default attribute handler __getattr__ has to return a function which subsequently (when it is called) knows which name caused it to be invoked. We do this by returning the actual function from inside a second function which provides storage for the name information - a closure - even later when the returned function is invoked.

1 comment

James Kilts 12 years, 12 months ago  # | flag

The second function call may not be necessary. The closure comes from the nested function referencing the variable "name." This seems to work on Python 2.4 and newer:

class C2:
    def __getattr__(self,name):
        def handlerFunction(*args,**kwargs):
            print name,args,kwargs
        return handlerFunction

# >>> c2 = C2()
# >>> c2.foo2(2,colors="red,green")
# foo2 (2,) {'colors': 'red,green'}
Created by mark andrew on Fri, 8 Oct 2004 (PSF)
Python recipes (4591)
mark andrew's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks