Newbie: switch question in Python

Neel Krishnaswami neelk at brick.cswv.com
Wed Dec 8 19:50:29 EST 1999


Aahz Maruch <aahz at netcom.com> wrote:
>In article <3847D902.EC9E3243 at compaq.com>,
>Greg Ewing  <greg.ewing at compaq.com> wrote:
>>
>>But unless you really need the speed, it's a lot clearer still just to
>>write a series of if...elifs.
>
>Maybe, unless you're loading code from a database, in which case the
>dict-based switch will be clearer *and* more efficient.

It's also clearer to use the dict if you need to do something that
needs double-dispatch. Then you can some variation of this:

class Foo:
    ...
    def binarymethod(self, other):
        return BinaryMethods[other.__class__](self, other)

This can reduce the number of places you need to change your code
when you add a class to the hierarchy. It's not as elegant as real
multiple dispatch, but it's not too bad...


Neel



More information about the Python-list mailing list