Working With the Python operator Module
Whenever you perform calculations in Python, you make use of built-in operators such as +
, %
, and **
. Did you know that Python also provides an operator
module? While it may seem that the purpose of operator
is to provide an alternative to these existing Python operators, the module actually has a far more specialized purpose than this.
The Python operator
module provides you with a set of functions, many of which correspond to the built-in operators but don’t replace them. The module also provides additional functionality, as you’ll soon discover.
In this tutorial, you’ll learn how to:
- Use any of the basic operator-equivalent functions
- Pass
operator
functions as arguments - Serialize
operator
functions for later use - Gauge
operator
function performance against common alternatives - Use higher-order
operator
functions in a range of interesting example cases
To get the most out of this tutorial, you should be familiar with the basic Python operators and the functional programming idea of one function returning another function back to its caller.
With that knowledge, you’re ready to dive in and learn how to use the greatly misunderstood operator
module to your advantage.
Get Your Code: Click here to download the free sample code that shows you how to use Python’s operator
module.
Using the Python operator
Module’s Basic Functions
In this section, you’ll learn about the operator
module’s operator-equivalent functions that mimic built-in operators, and you’ll pass them as arguments to higher-order functions. You’ll also learn how to save them for later use. Finally, you’ll investigate the performance of the operator-equivalent functions and uncover why you should never use them where a built-in Python operator will do instead.
Learning How the Basic Functions Work
The Python operator
module contains over forty functions, many of which are equivalent to the Python operators that you’re already familiar with. Here’s an example:
>>> import operator
>>> operator.add(5, 3) # 5 + 3
8
>>> operator.__add__(5, 3) # 5 + 3
8
Here, you add 5
and 3
together using both add()
and __add__()
. Both produce the same result. On the face of it, these functions provide you with the same functionality as the Python +
operator, but this isn’t their purpose.
Note: Most of the operator
module functions contain two names, a dunder version and a without-dunder version. In the previous example, operator.__add__(5, 3)
is the dunder version because it includes double underscores. From this point forward, you’ll use only the without-dunder versions, such as operator.add(5, 3)
. The dunder versions are for backward compatibility with the Python 2 version of operator
.
If you take a look at the list of functions that operator
provides for you, then you’ll discover that they cover not only the arithmetic operators, but also the equality, identity, Boolean, and even bitwise operators. Try out a random selection of them:
>>> operator.truediv(5, 2) # 5 / 2
2.5
>>> operator.ge(5, 2) # 5 >= 2
True
>>> operator.is_("X", "Y") # "X" is "Y"
False
>>> operator.not_(5 < 3) # not 5 < 3
True
>>> bin(operator.and_(0b101, 0b110)) # 0b101 & 0b110
'0b100'
In the code above, you work with a selection from the five main categories. First, you use the equivalent of an arithmetic operator, and then you try out equality and identity operator examples in the second and third examples, respectively. In the fourth example, you try a Boolean logical operator, while the final example uses a bitwise operator The comments show the equivalent Python operators.
Before reading the rest of this tutorial, feel free to take some time to experiment with the range of operator-equivalent functions that Python’s operator
module provides for you. You’ll learn how to use them next.
Passing Operators as Arguments Into Higher-Order Functions
You use the operator-equivalent functions most commonly as arguments for higher-order functions. You could write a higher-order function that performs a series of different tasks depending on the operator
function passed to it. Suppose, for example, you wanted a single function that could perform addition, subtraction, multiplication, and division. One messy way of doing this would be to use an if
… elif
statement as follows:
>>> def perform_operation(operator_string, operand1, operand2):
... if operator_string == "+":
... return operand1 + operand2
... elif operator_string == "-":
... return operand1 - operand2
... elif operator_string == "*":
... return operand1 * operand2
... elif operator_string == "/":
... return operand1 / operand2
... else:
... return "Invalid operator."
...
In your perform_operation()
function, the first parameter is a string representing one of the four basic arithmetic operations. To test the function, you pass in each of the four operators. The results are what you’d expect:
>>> number1 = 10
>>> number2 = 5
>>> calculations = ["+", "-", "*", "/"]
>>> for op_string in calculations:
... perform_operation(op_string, number1, number2)
...
15
5
50
2.0
This code is not only messy, but also limited to the four operators defined in the elif
clauses. Try, for example, passing in a modulo operator (%
), and the function will return an "Invalid operator"
message instead of the modulo division result that you were hoping for.
This is where you can make excellent use of the operator
functions. Passing these into a function gives you several advantages:
Read the full article at https://realpython.com/python-operator-module/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]