Codectionary / Developer documentation / Python

operator helpers

Use small standard-library callables for extracting fields and applying familiar operations.

How it works

operator exposes callable forms of operations and helpers such as itemgetter and attrgetter. These are useful when another API expects a function, for example a sorting key.

itemgetter uses subscription, while attrgetter reads attributes. They do not validate missing fields or supply automatic defaults. Choose a named function when extraction needs conditionals or error handling.

Limitations and practical choices

Prefer the form that makes the code easiest to read; a helper is not automatically better than a short lambda.

Attribute access can invoke properties, and overloaded operators can execute user-defined methods. These helpers do not make arbitrary objects safe to inspect.

Try it yourself

Sort records first by department and then by name using itemgetter with two keys. Compare it with a tuple-producing lambda.

Syntax

from operator import itemgetter
sorted(records, key=itemgetter("score"))

Examples

Sort dictionary records

Extract one field without an anonymous function.

from operator import itemgetter
records = [{"name": "John", "score": 3}, {"name": "James", "score": 1}]
ordered = sorted(records, key=itemgetter("score"))
print([row["name"] for row in ordered])
  1. itemgetter("score") creates a callable that reads record["score"]. sorted uses those integers as comparison keys.
  2. The records remain whole objects in the result. The final comprehension displays only their names.
  3. Use this when sorting records with a guaranteed field; a missing score would raise KeyError.
  4. Expected output: ['James', 'John']

Select multiple tuple positions

Build a smaller record from selected fields.

from operator import itemgetter
select = itemgetter(0, 2)
record = ("John", "internal-id", "London")
print(select(record))
  1. Two requested positions make the helper return a tuple containing those values in the requested order.
  2. Index one is not selected. This is extraction rather than mutation: record is unchanged.
  3. Use this for a small projection when positional record layouts are already clear and stable.
  4. Expected output: ('John', 'London')

Sort object attributes

Use attribute extraction rather than dictionary subscription.

from dataclasses import dataclass
from operator import attrgetter

@dataclass
class Job:
    name: str
    priority: int

jobs = [Job("Write", 2), Job("Read", 1)]
print([job.name for job in sorted(jobs, key=attrgetter("priority"))])
  1. Job instances expose priority as an attribute. attrgetter("priority") reads that field for the sorting key.
  2. itemgetter would instead require subscription support, which this class does not provide.
  3. Use the helper that matches the actual data representation rather than changing your records just for sorting.
  4. Expected output: ['Read', 'Write']

Best practices

  • Prefer the form that makes the code easiest to read; a helper is not automatically better than a short lambda.
  • Attribute access can invoke properties, and overloaded operators can execute user-defined methods. These helpers do not make arbitrary objects safe to inspect.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading