On this page
  1. operator
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Multi-Key Sorting with attrgetter & itemgetter
  7. 2. Calling a Named Method Across a Collection (methodcaller)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

operator

Prev: opcode | Up: stdlib_module | Next: optparse
Rel: itertools, functools
Ref: docs.python.org — operator
Tags: #public #python3 #stdlib


Import

import operator

Overview

C-implemented functional equivalents of Python's built-in operators (add, mul, lt, eq, and_) plus fast, picklable field extractors (itemgetter, attrgetter, methodcaller). Reach for itemgetter and attrgetter in sorted(), min(), max(), and itertools.groupby() instead of repetitive lambda functions.

Quick Start

from operator import attrgetter, itemgetter

rows = [("Ada", 95), ("Lin", 88), ("Grace", 99)]
assert sorted(rows, key=itemgetter(1), reverse=True)[0] == ("Grace", 99)

by_name = itemgetter("name")
assert by_name({"name": "Ada", "role": "admin"}) == "Ada"

Implementation Walkthrough

1. Multi-Key Sorting with attrgetter & itemgetter

Both support multi-key extraction (returning a tuple) and attrgetter even traverses dotted attribute paths:

from dataclasses import dataclass
from operator import attrgetter

@dataclass(frozen=True)
class Task:
    priority: int
    title: str

tasks = [Task(2, "b"), Task(1, "z"), Task(1, "a")]
ordered = sorted(tasks, key=attrgetter("priority", "title"))
assert [(t.priority, t.title) for t in ordered] == [(1, "a"), (1, "z"), (2, "b")]

2. Calling a Named Method Across a Collection (methodcaller)

from operator import methodcaller

words = ["  alpha  ", "  beta "]
cleaned = list(map(methodcaller("strip"), words))
assert cleaned == ["alpha", "beta"]

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes