summaryrefslogtreecommitdiffstats
path: root/Doc/library
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2011-01-08 09:35:38 (GMT)
committerRaymond Hettinger <python@rcn.com>2011-01-08 09:35:38 (GMT)
commit5254e9700ec0402d753e882d19d6df5522aa8cb5 (patch)
tree59788287cf5b14a5c0f4eac1804e334c22e1e938 /Doc/library
parent0ab10e460089fcdb9131ab1bdbe92142a76a83f3 (diff)
downloadcpython-5254e9700ec0402d753e882d19d6df5522aa8cb5.zip
cpython-5254e9700ec0402d753e882d19d6df5522aa8cb5.tar.gz
cpython-5254e9700ec0402d753e882d19d6df5522aa8cb5.tar.bz2
Issue 10533: Need example of using __missing__.
Diffstat (limited to 'Doc/library')
-rw-r--r--Doc/library/stdtypes.rst16
1 files changed, 14 insertions, 2 deletions
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index be0c8d5..be93ece 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -2117,8 +2117,20 @@ pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
returned or raised by the ``__missing__(key)`` call if the key is not
present. No other operations or methods invoke :meth:`__missing__`. If
:meth:`__missing__` is not defined, :exc:`KeyError` is raised.
- :meth:`__missing__` must be a method; it cannot be an instance variable. For
- an example, see :class:`collections.defaultdict`.
+ :meth:`__missing__` must be a method; it cannot be an instance variable::
+
+ >>> class Counter(dict):
+ ... def __missing__(self, key):
+ ... return 0
+ >>> c = Counter()
+ >>> c['red']
+ 0
+ >>> c['red'] += 1
+ >>> c['red']
+ 1
+
+ See :class:`collections.Counter` for a complete implementation including
+ other methods helpful for accumulating and managing tallies.
.. describe:: d[key] = value