ruk·si

# 🐍 Python - operator

Updated at 2018-11-19 17: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 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
{"ft_lang_label":"__label__en","ft_lang_prob":0.5158935,"math_prob":0.88758546,"size":1049,"snap":"2023-40-2023-50","text_gpt3_token_len":299,"char_repetition_ratio":0.119617224,"word_repetition_ratio":0.0,"special_character_ratio":0.31553861,"punctuation_ratio":0.1928934,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9876857,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-09-30T15:11:48Z\",\"WARC-Record-ID\":\"<urn:uuid:0691b6c1-2ada-4946-aa59-22449bce788a>\",\"Content-Length\":\"4628\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:c55d1fbe-4cac-409a-9cd0-98e1c66c6367>\",\"WARC-Concurrent-To\":\"<urn:uuid:26ce977e-405b-4898-9cab-1e955d43c75d>\",\"WARC-IP-Address\":\"178.62.225.138\",\"WARC-Target-URI\":\"https://ruk.si/notes/python/operator/\",\"WARC-Payload-Digest\":\"sha1:PZOFR3IJRPJAECGKLKOEUPCFAXULWWAX\",\"WARC-Block-Digest\":\"sha1:XQ7IHYSV3A2WT4FNCRZ5GWYQCE3VNGQB\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233510697.51_warc_CC-MAIN-20230930145921-20230930175921-00709.warc.gz\"}"}