Decorators for multimethods

R

Roman Suzi

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top