typestar

The operator module in Python

Named functions for the operators, which beats a lambda in a sort key.

from operator import attrgetter, itemgetter, methodcaller


class Step:
    def __init__(self, title, stars):
        self.title = title
        self.stars = stars

    def label(self):
        return self.title.upper()


rows = [("rust", 12), ("python", 6), ("sql", 3)]
print(sorted(rows, key=itemgetter(1), reverse=True))
print(list(map(itemgetter(0), rows)))

steps = [Step("slices", 2), Step("traits", 3)]
print([s.title for s in sorted(steps, key=attrgetter("stars"))])
print(list(map(methodcaller("label"), steps)))

How it works

  1. itemgetter and attrgetter are the common two.
  2. They are faster and clearer than an equivalent lambda.
  3. methodcaller calls a named method on each item.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
489
Tokens
167
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 95 seconds.

Type this snippet

Step 3 of 3 in functools & operator, step 40 of 53 in Pythonic Python.

← Previous Next →