summaryrefslogtreecommitdiffstats
path: root/Doc/library
diff options
context:
space:
mode:
authorBenjamin Peterson <benjamin@python.org>2010-08-21 20:08:36 (GMT)
committerBenjamin Peterson <benjamin@python.org>2010-08-21 20:08:36 (GMT)
commit2d55e2aab32b41004ef5c7b99fdcdeeb96611166 (patch)
tree0f0cd92eb4878baf6c8b693e051337dbd071abf6 /Doc/library
parentc16f8b33e05e6ba72f82f4ecca30e1c7ef9e7a8e (diff)
downloadcpython-2d55e2aab32b41004ef5c7b99fdcdeeb96611166.zip
cpython-2d55e2aab32b41004ef5c7b99fdcdeeb96611166.tar.gz
cpython-2d55e2aab32b41004ef5c7b99fdcdeeb96611166.tar.bz2
provide sample implementations for attrgetter and methodcaller
Diffstat (limited to 'Doc/library')
-rw-r--r--Doc/library/operator.rst25
1 files changed, 23 insertions, 2 deletions
diff --git a/Doc/library/operator.rst b/Doc/library/operator.rst
index 9e5354f..597be9d 100644
--- a/Doc/library/operator.rst
+++ b/Doc/library/operator.rst
@@ -333,7 +333,23 @@ expect a function argument.
attribute is requested, returns a tuple of attributes. After,
``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
- b.date)``.
+ b.date)``. Equivalent to::
+
+ def attrgetter(*items):
+ if len(items) == 1:
+ attr = items[0]
+ def g(obj):
+ return resolve_attr(obj, attr)
+ else:
+ def g(obj):
+ return tuple(resolve_att(obj, attr) for attr in items)
+ return g
+
+ def resolve_attr(obj, attr):
+ for name in attr.split("."):
+ obj = getattr(obj, name)
+ return obj
+
The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
the call ``f(b)`` returns ``b.date.month``.
@@ -383,7 +399,12 @@ expect a function argument.
additional arguments and/or keyword arguments are given, they will be given
to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
- call ``f(b)`` returns ``b.name('foo', bar=1)``.
+ call ``f(b)`` returns ``b.name('foo', bar=1)``. Equivalent to::
+
+ def methodcaller(name, *args, **kwargs):
+ def caller(obj):
+ return getattr(obj, name)(*args, **kwargs)
+ return caller
.. _operator-map: