Its sometimes useful to be able to access the functionality of an operator but as a function. For example to add two numbers together you could do.
>> print(1 + 2)
3
You could also do
>> import operator
>> print(operator.add(1, 2))
3
A use case for the function approach could be you need to write a calculator function which returns an answer given a simple formula.
import operator as _operator
operator_mapping = {
'+': _operator.add,
'-': _operator.sub,
'*': _operator.mul,
'/': _operator.truediv,
}
def calculate(formula):
x, operator, y = formula.split(' ')
# Convert x and y to floats so we can perform mathematical
# operations on them.
x, y = map(float, (x, y))
return operator_mapping[operator](x, y)
print(calculate('1 + 2')) # prints 3.0