Skip to content

Latest commit

 

History

History
38 lines (28 loc) · 1.8 KB

20220909162213.md

File metadata and controls

38 lines (28 loc) · 1.8 KB

operator.attrgetter

Similar to the operator module's itemgetter() I posted about the other day, you can also use attrgetter()

It returns a callable object that fetches attr from its operand - https://docs.python.org/3/library/operator.html#operator.attrgetter

This is pretty useful when sorting objects (example below).

>>> from collections import namedtuple
>>> from datetime import datetime, timedelta
>>> import operator
>>> from pprint import pprint as pp

>>> Transaction = namedtuple('Transaction', 'giver points date')

>>> tr1 = Transaction('Tim', 5, datetime.now())
>>> tr2 = Transaction('Sam', 2, datetime.now() - timedelta(days=1))
>>> tr3 = Transaction('Helen', 7, datetime.now() - timedelta(hours=8))
>>> transactions = [tr1, tr2, tr3]

>>> pp(sorted(transactions))  # sorts by giver
[Transaction(giver='Helen', points=7, date=datetime.datetime(2022, 9, 9, 8, 17, 10, 393997)),
 Transaction(giver='Sam', points=2, date=datetime.datetime(2022, 9, 8, 16, 17, 0, 330870)),
 Transaction(giver='Tim', points=5, date=datetime.datetime(2022, 9, 9, 16, 16, 40, 18263))]

>>> pp(sorted(transactions, key=operator.itemgetter(1)))  # sorts by points (2nd item)
[Transaction(giver='Sam', points=2, date=datetime.datetime(2022, 9, 8, 16, 17, 0, 330870)),
 Transaction(giver='Tim', points=5, date=datetime.datetime(2022, 9, 9, 16, 16, 40, 18263)),
 Transaction(giver='Helen', points=7, date=datetime.datetime(2022, 9, 9, 8, 17, 10, 393997))]

>>> pp(sorted(transactions, key=operator.attrgetter("date")))  # sorts by date attribute
[Transaction(giver='Sam', points=2, date=datetime.datetime(2022, 9, 8, 16, 17, 0, 330870)),
 Transaction(giver='Helen', points=7, date=datetime.datetime(2022, 9, 9, 8, 17, 10, 393997)),
 Transaction(giver='Tim', points=5, date=datetime.datetime(2022, 9, 9, 16, 16, 40, 18263))]

#operator #namedtuple