Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2d55e2a

Browse files
committed
provide sample implementations for attrgetter and methodcaller
1 parent c16f8b3 commit 2d55e2a

1 file changed

Lines changed: 23 additions & 2 deletions

File tree

Doc/library/operator.rst

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,23 @@ expect a function argument.
333333
attribute is requested, returns a tuple of attributes. After,
334334
``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
335335
``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
336-
b.date)``.
336+
b.date)``. Equivalent to::
337+
338+
def attrgetter(*items):
339+
if len(items) == 1:
340+
attr = items[0]
341+
def g(obj):
342+
return resolve_attr(obj, attr)
343+
else:
344+
def g(obj):
345+
return tuple(resolve_att(obj, attr) for attr in items)
346+
return g
347+
348+
def resolve_attr(obj, attr):
349+
for name in attr.split("."):
350+
obj = getattr(obj, name)
351+
return obj
352+
337353

338354
The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
339355
the call ``f(b)`` returns ``b.date.month``.
@@ -383,7 +399,12 @@ expect a function argument.
383399
additional arguments and/or keyword arguments are given, they will be given
384400
to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
385401
returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
386-
call ``f(b)`` returns ``b.name('foo', bar=1)``.
402+
call ``f(b)`` returns ``b.name('foo', bar=1)``. Equivalent to::
403+
404+
def methodcaller(name, *args, **kwargs):
405+
def caller(obj):
406+
return getattr(obj, name)(*args, **kwargs)
407+
return caller
387408

388409

389410
.. _operator-map:

0 commit comments

Comments
 (0)