decorators and multimethods
David Fraser
davidf at sjsoft.com
Thu Aug 19 05:13:22 EDT 2004
Michele Simionato wrote:
> 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).
Another benefit is you can give the different variants real names:
@foo.addmethod(object, object):
def add_objects(call_next, x, y):
return 'just two'
so you can call it directly if you want
David
More information about the Python-list
mailing list