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.

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.

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 ifelif 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 ]

Related Articles

Open Source Databases

We had a very fun and engaging chat with Matt Yonkovit who is the Chief Experience Officer at Percona, a service provider for open source databases like MySQL, PostgreSQL, MariaDB, and RocksDB. Matt has worked as a database architect for 10 years before transitioning into consulting roles at both MySQL and Sun Microsystems. In total, he’s been working with databases and open source for nearly 25 years.

Open Source Readiness

James has a lot of experience from both the developer side and the community side of open source. We dive deep into open source communities and enterprise involvement within those communities. Some of the topics we cover include: What is an open source readiness program and why should enterprises have one in place? Open source program offices and and the benefits of contributing to open source communities

Responses

Your email address will not be published. Required fields are marked *