getters
Variants of operator.attrgetter(), operator.itemgetter() and operator.methodcaller()
which operate on values within sequences.
New in version 3.2.0.
Classes:
|
Returns a callable object that fetches |
|
Returns a callable object that fetches |
|
Returns a callable object that calls the method name on the item at index |
-
class
attrgetter(idx, attr)[source] Returns a callable object that fetches
attrfrom the item at indexidxin its operand.The attribute name can contain dots. For example:
After
f = attrgetter(0, 'name'), the call callf(b)returnsb[0].name.After
f = attrgetter(3, 'name.first'), the callf(b)returnsb[3].name.first.
>>> from pathlib import Path >>> attrgetter(0, "name")([Path("dir/code.py")]) 'code.py' >>> attrgetter(2, "parent.name")([Path("dir/coincidence.py"), Path("dir/wheel.py"), Path("dir/operator.py")]) 'dir'
See also
-
class
itemgetter(idx, item)[source] Returns a callable object that fetches
itemfrom the item at indexidxin its operand, using the__getitem__()method.For example:
After
f = itemgetter(0, 2), the call callf(r)returnsr[0][2].After
g = itemgetter(3, 5), the callg(r)returnsr[3][5].
The items can be any type accepted by the item’s
__getitem__()method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice:>>> itemgetter(0, 1)(["ABCDEFG"]) 'B' >>> itemgetter(1, 2)(["ABC", "DEF"]) 'F' >>> itemgetter(0, slice(2, None))(["ABCDEFG"]) 'CDEFG' >>> army = [dict(rank="captain", name="Blackadder"), dict(rank="Private", name="Baldrick")] >>> itemgetter(0, "rank")(army) 'captain'
See also
-
class
methodcaller(_idx, _name, *args, **kwargs)[source] Returns a callable object that calls the method name on the item at index
idxin its operand.If additional arguments and/or keyword arguments are given, they will be passed to the method as well. For example:
After
f = methodcaller(0, 'name'), the callf(b)returnsb[0].name().After
f = methodcaller(1, 'name', 'foo', bar=1), the callf(b)returnsb[1].name('foo', bar=1).
>>> from datetime import date >>> methodcaller(0, "upper")(["hello", "world"]) 'HELLO' >>> methodcaller(1, "center", 9, '=')(["hello", "world"]) '==world==' >>> methodcaller(0, "replace", year=2019)([date(2021, 7, 6)]) datetime.date(2019, 7, 6)
See also
- Parameters
_idx – The index of the item to call the method on.
_attr – The name of the method to call.
*args – Positional arguments to pass to the method.
**kwargs – Keyword arguments to pass to the method.