ruk·si

🐍 Python
operator

Updated at 2018-11-19 19:51

Standard library operator module contains a lot of useful functional tools.

itemgetter helps picking items from squences.

from operator import itemgetter

animals = [
    ('Spider', 'small', 8),
    ('Dog', 'medium', 4),
    ('Human', 'medium', 2),
    ('Elephant', 'large', 4),
]

names = [a[0] for a in sorted(animals, key=itemgetter(2))]
assert names == ['Human', 'Dog', 'Elephant', 'Spider']

attrgetter helps picking attributes from objects.

from operator import attrgetter
from collections import namedtuple

Point = namedtuple('Point', 'x y')
points = [
    Point(x=1, y=2),
    Point(x=3, y=3),
    Point(x=5, y=4),
]

y_sorted = sorted(points, key=attrgetter('y'))
assert y_sorted == [Point(x=1, y=2), Point(x=3, y=3), Point(x=5, y=4)]

methodcaller  creates a function that calls a specific method on the argument object.

from operator import methodcaller
hiphenate = methodcaller('replace', ' ', '-')
assert hiphenate('my filename') == 'my-filename'

Source

  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho