Skip to content

Instantly share code, notes, and snippets.

@tekton
Created May 22, 2015 02:44
Show Gist options
  • Save tekton/736ba476aa416e413d2d to your computer and use it in GitHub Desktop.
Save tekton/736ba476aa416e413d2d to your computer and use it in GitHub Desktop.
operator_string_switch
"""
The goal here is to create a "switch" like environment to allow for using
strings and other representations for dynamic comparison of two values.
Uses the operator library: https://docs.python.org/2/library/operator.html
"""
import operator
OPS = {
'=': operator.eq,
'==': operator.eq,
'!=': operator.ne,
'>=': operator.gt,
'<=': operator.le,
'>': operator.gt,
'<': operator.lt,
'gt': operator.gt,
'gte': operator.gt,
}
def compute(valL, valR, op):
print OPS[op](valL, valR)
compute("a", "b", "!=")
compute(1, 1, "!=")
compute(1, 2, "!=")
compute(100, -999, "gte")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment