Sub topic 12
itemgetter, attrgetter and operator functions
This chapter assumes you can write lambdas, use key= with sorted, min and max, and call functools.partial. The operator module gives you ready-made function versions of Python's operators and of item and attribute access. They often replace the small lambdas you wrote in earlier chapters.
Why the operator module exists
Many lambdas only do one thing: index into an object, read an attribute, or apply an operator such as + or *. Python's standard library provides named functions for these jobs in the operator module.
from operator import add, itemgetter
print(add(2, 3)) # 5
print(itemgetter(1)(("a", "b"))) # bHere is the same idea as a table.
| Lambda | operator equivalent |
|---|---|
| `lambda a, b: a + b` | `operator.add` |
| `lambda a, b: a * b` | `operator.mul` |
| `lambda x: x[1]` | `operator.itemgetter(1)` |
| `lambda x: x["name"]` | `operator.itemgetter("name")` |
| `lambda x: x.age` | `operator.attrgetter("age")` |
| `lambda x: x.upper()` | `operator.methodcaller("upper")` |
Three reasons to prefer these functions:
- They state the intent by name, so the reader does not have to parse a lambda body.
- They are implemented in C in CPython, so they are usually a little faster than the equivalent lambda.
itemgetterandattrgettercan fetch several values at once, which a one-line lambda does only with extra syntax.
itemgetter
itemgetter(key) returns a callable. When you call it with an object, it returns obj[key]. It works with anything that supports []: lists, tuples, dictionaries, strings.
from operator import itemgetter
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(sorted(pairs, key=itemgetter(1)))
# [('pear', 1), ('fig', 2), ('apple', 3)]
second = itemgetter(1)
print(second(["x", "y", "z"])) # y
print(second("hello")) # eWith dictionaries, pass the key:
from operator import itemgetter
people = [
{"name": "Ana", "age": 31},
{"name": "Bo", "age": 25},
{"name": "Cy", "age": 40},
]
by_age = sorted(people, key=itemgetter("age"))
print([p["name"] for p in by_age]) # ['Bo', 'Ana', 'Cy']
oldest = max(people, key=itemgetter("age"))
print(oldest["name"]) # CyFetching several items
If you give itemgetter more than one argument, it returns a tuple of the results.
from operator import itemgetter
row = {"name": "Ana", "age": 31, "city": "Lima"}
get_name_city = itemgetter("name", "city")
print(get_name_city(row)) # ('Ana', 'Lima')This makes multi-field sorting short, because tuples compare element by element:
from operator import itemgetter
rows = [
{"team": "b", "score": 5},
{"team": "a", "score": 9},
{"team": "a", "score": 2},
]
print(sorted(rows, key=itemgetter("team", "score")))
# [{'team': 'a', 'score': 2}, {'team': 'a', 'score': 9}, {'team': 'b', 'score': 5}]Edge cases
- With one argument, the result is the bare value. With two or more, it is a tuple.
itemgetter(1)anditemgetter(1, 2)therefore return different shapes. - A missing key or index raises
KeyErrororIndexErrorwhen the getter is called, not when it is created. itemgetteralso accepts slices through thesliceobject:itemgetter(slice(0, 2))([10, 20, 30])returns[10, 20].
from operator import itemgetter
print(itemgetter(1)([10, 20, 30])) # 20
print(itemgetter(1, 2)([10, 20, 30])) # (20, 30)
print(itemgetter(slice(0, 2))([10, 20, 30])) # [10, 20]attrgetter
attrgetter(name) does the same for attributes: it returns a callable that gives obj.name. This suits class instances, dataclasses and named tuples.
from dataclasses import dataclass
from operator import attrgetter
@dataclass
class Player:
name: str
level: int
score: float
players = [
Player("Ana", 3, 88.5),
Player("Bo", 2, 92.0),
Player("Cy", 3, 75.0),
]
print([p.name for p in sorted(players, key=attrgetter("score"))])
# ['Cy', 'Ana', 'Bo']
print(max(players, key=attrgetter("level", "score")).name)
# AnaThe last line compares the tuples (level, score), so Ana (3, 88.5) beats Cy (3, 75.0) and Bo (2, 92.0).
Dotted names
attrgetter accepts dotted paths and follows them one attribute at a time. itemgetter has no equivalent for nested keys.
from operator import attrgetter
from types import SimpleNamespace
order = SimpleNamespace(customer=SimpleNamespace(address=SimpleNamespace(city="Oslo")))
print(attrgetter("customer.address.city")(order)) # OsloFor nested dictionaries you still need a lambda, such as lambda d: d["a"]["b"].
methodcaller
methodcaller(name, *args, **kwargs) returns a callable that calls the named method on its argument, passing the stored arguments.
from operator import methodcaller
words = [" Pear", "apple ", " Fig "]
print(list(map(methodcaller("strip"), words)))
# ['Pear', 'apple', 'Fig']
print(sorted(words, key=methodcaller("strip")))
# [' Pear', 'apple ', ' Fig '] is not what you want here, see belowThe second print does not sort by the stripped, case-insensitive text, because strip keeps the capital letters, and uppercase letters sort before lowercase ones. To get a case-insensitive order, build the key from a short lambda or from str.casefold after stripping. Here a lambda is the clearer tool, since the key needs two steps:
words = [" Pear", "apple ", " Fig "]
print(sorted(words, key=lambda w: w.strip().casefold()))
# ['apple ', ' Fig ', ' Pear']A good rule: when the key is a single method call, use methodcaller (or the unbound method, such as key=str.lower). When it combines steps, use a lambda.
Operator functions
The module has a function for almost every operator. Arithmetic: add, sub, mul, truediv, floordiv, mod, pow, neg. Comparison: eq, ne, lt, le, gt, ge. Logic and tests: not_, truth, is_, contains. Item access: getitem, setitem, delitem.
They are most useful as arguments to higher-order functions. reduce with operator.mul computes a product without a lambda:
from functools import reduce
from operator import mul
print(reduce(mul, [1, 2, 3, 4], 1)) # 24map accepts several iterables, so a two-argument operator function pairs them up:
from operator import add, sub
print(list(map(add, [1, 2, 3], [10, 20, 30]))) # [11, 22, 33]
print(list(map(sub, [10, 20, 30], [1, 2, 3]))) # [9, 18, 27]Combining with partial
partial fixes the first argument of a two-argument operator function. This builds a one-argument predicate or transformer without a lambda.
from functools import partial
from operator import gt, mul
triple = partial(mul, 3)
print(triple(7)) # 21
greater_than_two = partial(gt, 2) # gt(2, x) means 2 > x
print(list(filter(greater_than_two, [0, 1, 2, 3]))) # [0, 1]Watch the argument order. partial(gt, 2) is 2 > x, which means "x is less than 2". It does not mean "x is greater than 2". Mistakes like this are common, and a lambda (lambda x: x > 2) is clearer in that case.
Limits and gotchas
- Single argument only for getters.
itemgetterandattrgettertake one object. They cannot combine two parameters the waylambda a, b: a[0] + b[0]can. - No computation.
itemgetter(1)cannot returnx[1] * 2. Once you need arithmetic on the value, write a lambda. - Descending order. Use
reverse=Trueinsorted. You cannot negate a value withitemgetter. For mixed directions on several fields, sort in passes (Python's sort is stable) or use a lambda that negates numeric fields. - Mixed types. If the fetched values cannot be compared, for example
Nonewith an integer,sortedraisesTypeError, exactly as it does with a lambda key. - Late failure. Errors appear when the getter is called, so an invalid attribute name in
attrgetter("scroe")fails only during the sort.
Stable sorting makes mixed directions possible: sort by the secondary field first, then by the primary field.
from operator import itemgetter
rows = [
{"team": "b", "score": 5},
{"team": "a", "score": 9},
{"team": "a", "score": 2},
]
rows.sort(key=itemgetter("score"), reverse=True) # secondary: score, high first
rows.sort(key=itemgetter("team")) # primary: team, A to Z
print([(r["team"], r["score"]) for r in rows])
# [('a', 9), ('a', 2), ('b', 5)]Exercise
Given students = [{"name": "Ana", "grade": 90}, {"name": "Bo", "grade": 85}, {"name": "Cy", "grade": 90}], write one line that sorts the students by grade from highest to lowest, with ties broken by name from A to Z, using only operator helpers and sorted.
Show answer
A single itemgetter cannot sort grade descending and name ascending together. Use two stable passes: students.sort(key=itemgetter("name")); students.sort(key=itemgetter("grade"), reverse=True). The result is Ana (90), Cy (90), Bo (85). The name sort runs first so that ties keep name order after the grade sort.
Exercise
What does list(filter(partial(lt, 5), [3, 5, 7, 9])) return, and why?
Show answer
It returns [7, 9]. partial(lt, 5) fixes the first argument, so each call is lt(5, x), which is 5 < x. Only 7 and 9 are greater than 5.
Exercise
Which expression returns a tuple, and which returns a bare value: itemgetter("a")(d) or itemgetter("a", "b")(d)?
Show answer
itemgetter("a")(d) returns the bare value d["a"]. itemgetter("a", "b")(d) returns the tuple (d["a"], d["b"]).