Skip to content

Instantly share code, notes, and snippets.

@blaylockbk
Created February 5, 2020 21:12
Show Gist options
  • Save blaylockbk/a4d7346e37ad0ce902b30fa7adc21280 to your computer and use it in GitHub Desktop.
Save blaylockbk/a4d7346e37ad0ce902b30fa7adc21280 to your computer and use it in GitHub Desktop.
Performs an operation when you have an operator as a string.
def str_operator(left, operator_str, right):
"""
Performs an operation when you have an operator as a string.
An alternative method is to use the `eval()` function, if you aren't
worried about the security vulnerabilities.
Example, `eval('a + b')` where a=5 and b=6 will result in 11.
Parameters
----------
left :
A value or array on the left side of the operato.
operator_str : {'>', '>=', '==', '<', '<=', '+', '-', '*', '/', '//', '%', '**', 'is', 'is not', 'in'}
An operator as a string.
right :
A value or array on the right side of the operator.
Returns
-------
The results of the operation. This isn't heart surgery.
Examples
--------
>>> a = 5
>>> b = 6
>>> c = np.array([3, 5, 7])
>>> a > b
False
is the same as...
>>> str_operator(a, '>', b)
False
>>> a > c
array([ True, False, False])
is the same as...
>>> str_operator(a, '>', c)
array([ True, False, False])
>>> a + c
array([ 8, 10, 12])
is the same as...
>>> str_operator(a, '+', c)
array([ 8, 10, 12])
"""
op_list = {'>': operator.gt,
'>=': operator.ge,
'==': operator.eq,
'<': operator.lt,
'<=': operator.le,
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
'//': operator.floordiv,
'%': operator.mod,
'**': operator.pow,
'is': operator.is_,
'is not': operator.is_not,
'in': operator.contains,
}
assert operator_str in list(op_list), f"`operator_str` must be one of {list(op_list)}"
return op_list[operator_str](left, right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment