Search code examples
pythonoperators

Why do we need operator functions in python?


Why would one use operators in python when we have almost all of them available inline such as [/,*,-,+,<,>,...]?

When would we need to use these operator functions as opposed to the inline operators?


Solution

  • As an example of why you might like to be able to call an operator as a function, consider the following code:

        if op == "+":
            return num1 + num2
        elif op == "-":
            return num1 - num2
        elif op == "*":
            return num1 * num2
        else:
            raise ValueError(f"invalid operator {op}")
    

    With operator this can be written more easily as:

        return {
            "+": operator.add,
            "-": operator.sub,
            "*": operator.mul,
        }[op](num1, num2)