decorators and multimethods

Michele Simionato michele.simionato at
Sat Aug 7 17:42:06 CEST 2004

michele.simionato at (Michele Simionato) wrote in message news:<4edc17eb.0408062340.71ab270f at>...

<snip using decorators as syntactic sugar over Howard Stearns module>

Martin v. Lewis suggested an improvement, which involves adding the 
following method to the Generic_Function class:

    def addmethod(self, *types):
        "My own tiny modification to Stearns code"
        return lambda f: self.setdefault(types,f)

The advantage is that methods definitions can go in any scope now and
not only at the top level as in my original hack.
My previous example read:

foo = Generic_Function()

@foo.addmethod(object, object, object)
def _(call_next, x, y, z):
   return 'default'

@foo.addmethod(int, int, int)
def _(call_next, x, y, z):
   return 'all ints , ' + call_next(x, y, z)

@foo.addmethod(object, object)
def _(call_next, x, y):
   return 'just two'

where I use "_" as a poor man anonymous function. I cannot reuse the name
"foo" now, since

def foo(..):

is really converted to

def foo(..)


and this would correctly raise a "foo function has not attribute addmethod"!
But in some sense this is better, since we avoid any confusion
between the member functions and the generic function (which is implemented
as a dictionary, BTW).

        Michele Simionato

More information about the Python-list mailing list