Decorators for multimethods

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


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":

    import Multimethod

    class Foo: pass

    class Bar(Foo): pass

    def multimethod(g, *args):
      def make_multimethod(func):
        mm = Multimethod.Method(tuple(args), func)
        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'

        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 =\= My AI powered by GNU/Linux RedHat 7.3

More information about the Python-list mailing list