Skip to content

Instantly share code, notes, and snippets.

@gatesphere
Last active December 26, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gatesphere/7201086 to your computer and use it in GitHub Desktop.
Save gatesphere/7201086 to your computer and use it in GitHub Desktop.
Passing comparison operators in Python
## approach 1
def myfun(a, b, mode='<'):
valid_modes = ['<', '<=', '>', '>=', '==', '!=']
if mode not in valid_modes:
print 'Error!'
... # error handling code here
return
if mode == '<':
if a < b:
...
elif mode == '<=':
if a <= b:
...
elif mode == '>':
if a > b:
...
elif mode == '>=':
if a >= b:
...
elif mode == '==':
if a == b:
...
elif mode == '!=':
if a != b:
...
else:
print 'Something went horribly wrong. Blame cosmic rays.'
## approach 2
# comparators
cmp_lt = lambda x,y: x < y
cmp_gt = lambda x,y: x > y
cmp_eq = lambda x,y: x == y
cmp_lte = lambda x,y: x <= y
cmp_gte = lambda x,y: x >= y
cmp_neq = lambda x,y: x != y
def myfun(a, b, comparator):
if comparator(a,b):
...
## python is batteries included!
import operator
def myfun(a, b, comparator):
if comparator(a,b):
...
## don't do this, dummy
def myfun(a, b, mode='<'):
if eval(str(a)+mode+str(b)):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment