The operator Module in Python: itemgetter, attrgetter, methodcaller

Modified: | Tags: Python

In Python, the operator module provides functions for the built-in operators and functions to create callable objects that fetch items, attributes, and call methods.

operator.itemgetter(), operator.attrgetter(), and operator.methodcaller() are often used for the key argument in functions like sorted(). See the following article for details.

Functions in the operator module corresponding to built-in operators

The operator module provides functions corresponding to the built-in operators.

This section describes some of them. For a complete list, see the table in the official documentation.

Arithmetic operators

Python has arithmetic operators such as + and *.

For example, operator.add(a, b) is equivalent to a + b.

import operator

print(2 + 3)
# 5

print(operator.add(2, 3))
# 5

Functions for the -, *, /, and // operators are also provided.

print(operator.sub(2, 3))  # 2 - 3
# -1

print(operator.mul(2, 3))  # 2 * 3
# 6

print(operator.truediv(2, 3))  # 2 / 3
# 0.6666666666666666

print(operator.floordiv(2, 3))  # 2 // 3
# 0

Comparison operators

Functions for comparison operators, such as < and ==, are also provided.

print(operator.lt(2, 3))  # 2 < 3
# True

print(operator.le(2, 3))  # 2 <= 3
# True

print(operator.gt(2, 3))  # 2 > 3
# False

print(operator.ge(2, 3))  # 2 >= 3
# False

print(operator.eq(2, 3))  # 2 == 3
# False

print(operator.ne(2, 3))  # 2 != 3
# True

Bitwise operators

Functions for bitwise operators, such as & (AND), | (OR), and ^ (XOR), are also provided.

In the following example, the prefix 0b is used to denote an integer (int) in binary format. Then, the result is converted back to a binary string representation using the bin() function.

print(bin(0b1100 & 0b1010))
# 0b1000

print(bin(operator.and_(0b1100, 0b1010)))
# 0b1000

print(bin(0b1100 | 0b1010))
# 0b1110

print(bin(operator.or_(0b1100, 0b1010)))
# 0b1110

print(bin(0b1100 ^ 0b1010))
# 0b110

print(bin(operator.xor(0b1100, 0b1010)))
# 0b110

Note that, while the names are operator.and_() and operator.or_(), their results differ from the and and or operators.

print(bin(0b1100 and 0b1010))
# 0b1010

print(bin(0b1100 or 0b1010))
# 0b1100

The and and or operators evaluate the truthiness of the left and right operands and directly return the left or the right value, as shown in the example above. See the following article for details.

As of Python 3.11, the operator module does not provide functions for the and and or operators.

Get an item from an object: operator.itemgetter()

operator.itemgetter() returns a callable object that fetches an item from an object. It corresponds to specifying an index with [].

l = [0, 10, 20, 30, 40, 50]

print(l[3])
# 30

f = operator.itemgetter(3)
print(f(l))
# 30

Unlike functions corresponding to the built-in operators, such as operator.add(), operator.itemgetter() returns a callable object.

It may seem strange to have () in succession, but it can also be written as follows.

print(operator.itemgetter(3)(l))
# 30

Like [], a negative value can indicate a position counted from the end.

print(l[-1])
# 50

print(operator.itemgetter(-1)(l))
# 50

You can use the slice() function to specify a slice.

print(l[1:4])
# [10, 20, 30]

print(operator.itemgetter(slice(1, 4))(l))
# [10, 20, 30]

print(l[1::2])
# [10, 30, 50]

print(operator.itemgetter(slice(1, None, 2))(l))
# [10, 30, 50]

Multiple values can be specified as arguments to operator.itemgetter(), which returns a tuple with the results for each specified value.

print(operator.itemgetter(0, slice(1, 4), -1)(l))
# (0, [10, 20, 30], 50)

print(type(operator.itemgetter(0, slice(1, 4), -1)(l)))
# <class 'tuple'>

operator.itemgetter() fetches items by __getitem__(). It also supports getting values by specifying keys of a dictionary (dict).

d = {'k1': 0, 'k2': 10, 'k3': 20}

print(d['k2'])
# 10

print(operator.itemgetter('k2')(d))
# 10

print(operator.itemgetter('k2', 'k1')(d))
# (10, 0)

For example, operator.itemgetter() is used for the key argument of the sorted() function and others. See the following article for details.

Get an attribute from an object: operator.attrgetter()

operator.attrgetter() returns a callable object that fetches an attribute from an object. It corresponds to specifying an attribute name like .xxx.

Consider a datetime.date object that stores date information.

import datetime

dt = datetime.date(2001, 10, 20)
print(dt)
# 2001-10-20

print(type(dt))
# <class 'datetime.date'>

print(dt.year)
# 2001

Like operator.itemgetter(), operator.attrgetter() can also fetch multiple attributes at once.

f = operator.attrgetter('year')
print(f(dt))
# 2001

print(operator.attrgetter('year', 'month', 'day')(dt))
# (2001, 10, 20)

Call a method on an object: operator.methodcaller()

operator.methodcaller() returns a callable object that calls a method on an object.

s = 'xxxAyyyAzzz'

print(s.upper())
# XXXAYYYAZZZ

f = operator.methodcaller('upper')
print(f(s))
# XXXAYYYAZZZ

You can also specify arguments for the method.

print(s.split('A', maxsplit=1))
# ['xxx', 'yyyAzzz']

print(operator.methodcaller('split', 'A', maxsplit=1)(s))
# ['xxx', 'yyyAzzz']

Along with operator.itemgetter(), both operator.attrgetter() and operator.methodcaller() can also be used to specify the key argument for functions such as sorted().

Related Categories

Related Articles