Decorators for multimethods

Roman Suzi rnd at onego.ru
Fri Dec 10 21:52:29 CET 2004


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
-- 
rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3



More information about the Python-list mailing list