Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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)


I 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: