Optimizing multiple dispatch

Jacek Generowicz jacek.generowicz at cern.ch
Thu Jun 3 08:35:54 EDT 2004


I have a multiple disptacher which, conceptually, looks something like
this:



class Multimethod:

    def __init__(self):
        self.methods = {}

    def __call__(self, *args):
        return self.methods[tuple(map(type, args))](*args)

    def add_method(self, method, *types):
        self.methods[types] = method

foo = Multimethod()

def fooii(a, b):
    print "We got two ints"

def foosb(a, b):
    print "We got a string and a bar"

class bar(object): pass

foo.add_method(fooii, int, int)
foo.add_method(foosb, str, bar)

foo(1,2)
foo("a string", bar())



My actual code looks nothing like this[*], because it contains a
number of optimizations, and addresses some domain-specific
considerations which are not relevant in this context; but the code
shown should highlight the salient points.

Profiling suggests that "tuple(map(type, args))" is taking a
significant proportion of time in certain critical loops.

Do you have any suggestions about how to make in run faster? (Either
by optimizing "tuple(map(type, args)", or by using a completely
different organization for the whole thing. There is almost certainly
no point in addressing any other implementation detail[*] of what is
shown here, as it is likely to be absent from my real code.)


[*] For example, there is no __call__ in my implementation; it's
    implementeted as a closure.



More information about the Python-list mailing list