does a switch idiom make sense in this case?

Posted by the ungoverned on Stack Overflow See other posts from Stack Overflow or by the ungoverned
Published on 2010-03-17T16:32:54Z Indexed on 2010/03/17 16:41 UTC
Read the original article Hit count: 264

I'm writing a parser/handler for a network protocol; the protocol is predefined and I am writing an adapter, in python.

In the process of decoding the incoming messages, I've been considering using the idiom I've seen suggested elsewhere for "switch" in python: use a hash table whose keys are the field you want to match on (a string in this case) and whose values are callable expressions:

 self.switchTab = { 'N': self.handleN,
                    'M': self.handleM,
                     ...
                  }

Where self.handleN, etc., are methods on the current class.

The actual switch looks like this:

 self.switchTab[selector]()

According to some profiling I've done with cProfile (and Python 2.5.2) this is actually a little bit faster than a chain of if..elif... statements.

My question is, do folks think this is a reasonable choice? I can't imagine that re-framing this in terms of objects and polymorphism would be as fast, and I think the code looks reasonably clear to a reader.

© Stack Overflow or respective owner

Related posts about python

Related posts about switch-statement