decorators and multimethods

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


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

<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

@foo.addmethod(...)
def foo(..):
 ....

is really converted to

def foo(..)
 ...

foo=foo.addmethod(...)(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