[BangPypers] Clojure style multimethod functions in python

Baishampayan Ghose b.ghose at gmail.com
Mon Aug 23 17:06:54 CEST 2010


Dhananjay,

> Could you help explain in light of the following (the argument lists are in
> bold). The switcher function is provided exactly the same arguments as the
> various multimethods. Probably something about clojure I am not aware of ?
>
> Dhananjay
>
> def multi(switcher_func):
>    """ Declares a multi map based method which will switch to the
>    appropriate function based on the results of the switcher func"""
>
>    def dispatcher(*args, **kwargs):
>        key = *switcher_func(*args, **kwargs)*
>        func = dispatcher.dispatch_map[key]
>        if func :
>            return *func(*args,**kwargs)*
>        else :
>            raise Exception("No function defined for dispatch key: %s" % key
> )
>    dispatcher.dispatch_map = {}
>    return dispatcher

Multimethods are supposed to dispatch on the ``value'' returned by the
dispatch function and not just when a specific condition is satisfied.
What will you do when there are multiple possibilities? Ideally, I
should be able to prefer a specific method to another one in case
there is some ambiguity. Yours will always pick the first one that
satisfies the condition, which is again dependent on the order in
which the code is evaluated.

For example, try implementing the following using your code -
http://clojure.org/runtime_polymorphism

Regards,
BG

-- 
Baishampayan Ghose
b.ghose at gmail.com


More information about the BangPypers mailing list