diff options
author | Terry Jan Reedy <tjreedy@udel.edu> | 2014-12-10 23:38:07 (GMT) |
---|---|---|
committer | Terry Jan Reedy <tjreedy@udel.edu> | 2014-12-10 23:38:07 (GMT) |
commit | f0f09b947002bda07a23a35dfa2f00dc29e3cdd7 (patch) | |
tree | f4d68049d1a6fcf4e71a5b0fe3ffff650a4b6067 /Doc/library/stdtypes.rst | |
parent | e6b42438fa53f7bcadc12bdcfa491b99f280f115 (diff) | |
download | cpython-f0f09b947002bda07a23a35dfa2f00dc29e3cdd7.zip cpython-f0f09b947002bda07a23a35dfa2f00dc29e3cdd7.tar.gz cpython-f0f09b947002bda07a23a35dfa2f00dc29e3cdd7.tar.bz2 |
Issue #23006: Improve the documentation and indexing of dict.__missing__.
Add an entry in the language datamodel special methods section.
Revise and index its discussion in the stdtypes mapping/dict section.
Backport the code example from 3.4.
Diffstat (limited to 'Doc/library/stdtypes.rst')
-rw-r--r-- | Doc/library/stdtypes.rst | 34 |
1 files changed, 25 insertions, 9 deletions
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index fa4304c..bc437a4 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -2031,16 +2031,32 @@ pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is not in the map. + .. index:: __missing__() + + If a subclass of dict defines a method :meth:`__missing__` and *key* + is not present, the ``d[key]`` operation calls that method with the key *key* + as argument. The ``d[key]`` operation then returns or raises whatever is + returned or raised by the ``__missing__(key)`` call. + 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:: + + >>> class Counter(dict): + ... def __missing__(self, key): + ... return 0 + >>> c = Counter() + >>> c['red'] + 0 + >>> c['red'] += 1 + >>> c['red'] + 1 + + The example above shows part of the implementation of + :class:`collections.Counter`. A different ``__missing__`` method is used + by :class:`collections.defaultdict`. + .. versionadded:: 2.5 - If a subclass of dict defines a method :meth:`__missing__`, if the key - *key* is not present, the ``d[key]`` operation calls that method with - the key *key* as argument. The ``d[key]`` operation then returns or - raises whatever is 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`. + Recognition of __missing__ methods of dict subclasses. .. describe:: d[key] = value |