The operator
Module
The standard library’s operator
module provides a set of functions that correspond to Python’s intrinsic operators. For example, operator.add(x, y)
is equivalent to the expression x + y
.
While this might seem redundant at first, these functions are incredibly useful when you need to pass an operation as an argument to another function, a common pattern in functional programming.
1. Functional Equivalents of Operators
Instead of using a lambda
function to perform a simple operation, you can often use a more efficient and readable function from the operator
module.
Pyground
Use `functools.reduce` to calculate the product of all numbers in a list. Compare using a `lambda` vs. `operator.mul`.
Expected Output:
Product with lambda: 120 Product with operator.mul: 120
Output:
2. The “Getter” Functions: itemgetter
, attrgetter
, and methodcaller
This is where the operator
module truly shines. It provides powerful, efficient functions for creating callables that retrieve data from objects. These are most commonly used as the key
argument for sorting functions like sorted()
and list.sort()
.
operator.itemgetter
Creates a callable that retrieves an item from an object using the __getitem__
method. It’s perfect for sorting lists of tuples or dictionaries.
Pyground
You have a list of user tuples `(name, score)`. Sort them by score in descending order.
Expected Output:
Sorted by score: [('Charlie', 95), ('Alice', 92), ('Bob', 85)]
Output:
You can also pass multiple indices to itemgetter
to retrieve multiple items at once.
Pyground
From a list of records, extract just the name and country for each.
Expected Output:
John Doe is from USA Jane Smith is from UK Taro Yamada is from JP
Output:
Why use these?
- Speed:
itemgetter
andattrgetter
are written in C and are significantly faster than equivalentlambda
functions. - Readability:
key=operator.attrgetter('gpa')
can be more explicit and readable thankey=lambda s: s.gpa
. - Conciseness: They provide a clean, functional way to express common data extraction patterns.
3. In-Place Operators
The module also provides functional equivalents for in-place (augmented) assignment operators, like operator.iadd
for +=
. These are used less frequently but are available for scenarios that require them.
Pyground
Use `operator.iadd` to concatenate two lists in-place.
Expected Output:
list_b was modified: [1, 2, 3, 4, 5] list_a sees the change: [1, 2, 3, 4, 5]