Skip to content

Instantly share code, notes, and snippets.

@dominic
Last active December 20, 2015 15:08
Show Gist options
  • Save dominic/6152032 to your computer and use it in GitHub Desktop.
Save dominic/6152032 to your computer and use it in GitHub Desktop.
How to remove branching logic in Python
"""
Before
"""
...
if lex_token['id']=='INT':
yield LiteralToken(lex_token['value'])
elif lex_token['id']=='ADD_OP':
yield OperatorAddToken()
elif lex_token['id']=='SUB_OP':
yield OperatorSubToken()
elif lex_token['id']=='MUL_OP':
yield OperatorMulToken()
elif lex_token['id']=='DIV_OP':
yield OperatorDivToken()
elif lex_token['id']=='POW_OP':
yield OperatorPowToken()
...
"""
After
"""
tokenize_values = {
'INT': LiteralToken,
'ADD_OP': OperatorAddToken
}
def tokenize(program):
for lex_token in lex_tokens:
tokenize_values[lex_token['id']](lex_token['value'])
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment