A puzzle Re: Decorators for multimethods
Roman Suzi
rnd at onego.ru
Fri Dec 10 16:26:58 EST 2004
For those who want to exercize Python skills, there is a problem
below for defining multimethod g with as simple syntax as possible:
@MULTIMETHOD
def g(x, y):
@PART(Foo, Foo)
def m1(a, b): return 'foofoo'
@PART(Foo, Bar)
def m2(a, b): return 'foobar'
@PART(Bar, Foo)
def m3(a, b): return 'barfoo'
What are definitions of MULTIMETHOD and PART in this case?
(if such are at all possible).
My best result was with
class G(MMCLASS):
def define(self):
@self.PART(Foo, Foo)
def m1(a, b): return 'foofoo'
@self.PART(Foo, Bar)
def m2(a, b): return 'foobar'
@self.PART(Bar, Foo)
def m3(a, b): return 'barfoo'
g = G()
where
class MMCLASS(Multimethod.Generic):
def __init__(self):
Multimethod.Generic.__init__(self)
def PART(*args):
def make_multimethod(func):
mm = Multimethod.Method(tuple(args), func)
print func
self.add_method(mm)
return mm
return make_multimethod
self.PART = PART
self.define()
On Fri, 10 Dec 2004, Roman Suzi wrote:
>
>hi!
>
>I've found one more nice use case for decorators. I feel multimethods
>could be made even nicier by defining multimethods inside special
>class. But I have not figured out how to do it yet.
>
>#!/bin/env python2.4
>if "We have Neel Krishnaswami module Multimethod.py":
>
> import Multimethod
>
> class Foo: pass
>
> class Bar(Foo): pass
>
> def multimethod(g, *args):
> def make_multimethod(func):
> mm = Multimethod.Method(tuple(args), func)
> g.add_method(mm)
> return mm
> return make_multimethod
>
> g = Multimethod.Generic()
>
> @multimethod(g, Foo, Foo)
> def m1(a, b): return 'foofoo'
>
> @multimethod(g, Foo, Bar)
> def m2(a, b): return 'foobar'
>
> @multimethod(g, Bar, Foo)
> def m3(a, b): return 'barfoo'
>
> try:
> print 'Argtypes ', 'Result'
> print 'Foo, Foo:', g(Foo(), Foo())
> print 'Foo, Bar:', g(Foo(), Bar())
> print 'Bar, Foo:', g(Bar(), Foo())
> print 'Bar, Bar:', g(Bar(), Bar())
> except Multimethod.AmbiguousMethodError:
> print 'Failed due to AmbiguousMethodError'
>
>
>Sincerely yours, Roman Suzi
>
Sincerely yours, Roman Suzi
--
rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3
More information about the Python-list
mailing list