title: Python state-machine design
body: <p>Related to <strong><a href="https://stackoverflow.com/questions/1647631/c-state-machine-design">this Stack&nbsp;Overflow question (C state-machine design)</a></strong>, could you Stack&nbsp;Overflow folks share your Python state-machine design techniques with me (and the community)?</p>
  
  <p>At the moment, I am going for an engine based on the following:</p>
  
  <pre><code>class TrackInfoHandler(object):
      def __init__(self):
          self._state="begin"
          self._acc=""
  
      ## ================================== Event callbacks
  
      def startElement(self, name, attrs):
          self._dispatch(("startElement", name, attrs))
  
      def characters(self, ch):
          self._acc+=ch
  
      def endElement(self, name):
          self._dispatch(("endElement", self._acc))
          self._acc=""
  
      ## ===================================
      def _missingState(self, _event):
          raise HandlerException("missing state(%s)" % self._state)
  
      def _dispatch(self, event):
          methodName="st_"+self._state
          getattr(self, methodName, self._missingState)(event)
  
      ## =================================== State related callbacks
  </code></pre>
  
  <p>But I am sure there are tons of ways of going at it while leveraging Python's dynamic nature (e.g. dynamic dispatching).</p>
  
  <p>I am after design techniques for the "engine" that receives the "events" and "dispatches" against those based on the "state" of the machine.</p>