[Python-Dev] switch-based programming in Python

Greg Ewing greg@cosc.canterbury.ac.nz
2001年11月09日 15:50:32 +1300 (NZDT)


As an example of a real-life application which might
benefit from a fast switch-statement in Python, I'd
like to offer the following excerpt from Plex, which
runs as part of a tight loop once per input character.
 if input_state == 1:
 cur_pos = next_pos
 # Begin inlined: c = self.read_char()
 buf_index = next_pos - buf_start_pos
 if buf_index < buf_len:
 c = buffer[buf_index]
 next_pos = next_pos + 1
 else:
 discard = self.start_pos - buf_start_pos
 data = self.stream.read(0x1000)
 buffer = self.buffer[discard:] + data
 self.buffer = buffer
 buf_start_pos = buf_start_pos + discard
 self.buf_start_pos = buf_start_pos
 buf_len = len(buffer)
 buf_index = buf_index - discard
 if data:
 c = buffer[buf_index]
 next_pos = next_pos + 1
 else:
 c = ''
 # End inlined: c = self.read_char()
 if c == '\n':
 cur_char = EOL
 input_state = 2
 elif not c:
 cur_char = EOL
 input_state = 4
 else:
 cur_char = c
 elif input_state == 2:
 cur_char = '\n'
 input_state = 3
 elif input_state == 3:
 cur_line = cur_line + 1
 cur_line_start = cur_pos = next_pos
 cur_char = BOL
 input_state = 1
 elif input_state == 4:
 cur_char = EOF
 input_state = 5
 else: # input_state = 5
 cur_char = ''
 # End inlined self.next_char()
 else: # not new_state
 if trace: #TRACE#
 print "blocked" #TRACE#
 # Begin inlined: action = self.back_up()
 if backup_state:
 (action, cur_pos, cur_line, cur_line_start, 
 cur_char, input_state, next_pos) = backup_state
 else:
 action = None
 break # while 1
 # End inlined: action = self.back_up()
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	 | A citizen of NewZealandCorp, a	 |
Christchurch, New Zealand	 | wholly-owned subsidiary of USA Inc. |
greg@cosc.canterbury.ac.nz	 +--------------------------------------+

AltStyle によって変換されたページ (->オリジナル) /