
pje at telecommunity
Aug 14, 2004, 12:02 PM
Post #8 of 9
(495 views)
Permalink
|
michele.simionato[at]gmail.com (Michele Simionato) wrote in message news:<4edc17eb.0408062340.71ab270f[at]posting.google.com>... > > One trick is to use decorators to implement multimethods. A while ago > Howard Stearns posted here a recipe to implement generic functions > a.k.a multimethods. > > I have not studied his recipe, so don't ask me how it works. All I > did was to add an "addmethod" function and save his code in a module > called genericfunctions. > > Decorators allowed me to use the following syntax: > > # BEGIN generic functions in Python, example > # use code and examples from Howard Stearns > > from genericfunctions import Generic_Function, addmethod > > foo = Generic_Function() > > @addmethod(object, object, object) > def foo(_, x, y, z): > return 'default' > > @addmethod(int, int, int) > def foo(call_next, x, y, z): > return 'all ints , ' + call_next(x, y, z) > > @addmethod(object, object) > def foo( _, x, y): > return 'just two' FYI, there's another example of this approach available in PyProtocols CVS; see: http://www.eby-sarna.com/pipermail/peak/2004-July/001598.html It uses this syntax: from protocols.dispatch import when, next_method [when("True")] def foo(x,y,z): return "default" [.when("x in int and y in int and z in int")] def foo(x,y,z): return "all ints, "+next_method(x,y,z) but will work with Python 2.2.2 and up. It also allows arbitrary expressions to be used to distinguish multimethod cases, not just type information, but still optimizes them to table lookups. It doesn't support variadic or default arguments yet, though. -- http://mail.python.org/mailman/listinfo/python-list
|