4 ms·
Suppose you are dispatching on token types. You could write something like this: handlers = {'start' : handle_start, 'jump' : handle_jump, 'end' : handle_e
by bjourne 6y ago
Suppose you are dispatching on token types. You could write something like this:
handlers = {'start' : handle_start, 'jump' : handle_jump, 'end' : handle_end, ...}
for tok, arg in tokens:
if tok not in handlers:
raise ValueError('Wrong token type, must be any of %s.' % ', '.join(handlers))
handlers[tok](arg)
- hnlmorg 6y agoI see, I do follow that design pattern for larger switch statements or where the dictionary had to be dynamically populated (even in non-Python languages) but I hadn't considered using it for smaller switch statements as well. Thank you for the example.