Skip to content

Commit 127ba72

Browse files
committed
rewrite the documentation of defaultdict.__missing__
1 parent a0a63f1 commit 127ba72

1 file changed

Lines changed: 16 additions & 17 deletions

File tree

Doc/library/collections.rst

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -752,23 +752,22 @@ stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
752752

753753
.. method:: __missing__(key, /)
754754

755-
If the :attr:`default_factory` attribute is ``None``, this raises a
756-
:exc:`KeyError` exception with the *key* as argument.
757-
758-
If :attr:`default_factory` is not ``None``, it is called without arguments
759-
to provide a default value for the given *key*, this value is inserted in
760-
the dictionary for the *key*, and returned.
761-
762-
If calling :attr:`default_factory` raises an exception this exception is
763-
propagated unchanged.
764-
765-
This method is called by the :meth:`__getitem__` method when the requested
766-
key is not found; whatever it returns or raises is then returned or raised
767-
by :meth:`__getitem__`.
768-
769-
Note that :meth:`__missing__` is *not* called for any operations besides
770-
`self[key]`. This means that `self.get(key)` will, like normal dictionaries,
771-
return ``None`` as a default rather than using :attr:`default_factory`.
755+
Equivalent to::
756+
757+
if self.default_factory is None:
758+
raise KeyError(key)
759+
self[key] = value = self.default_factory()
760+
return value
761+
762+
Keep in mind that this method is *not* called for any operations besides
763+
``dd[key]``. This means that ``dd.get(key)`` will, like normal
764+
dictionaries, return ``None`` as a default rather than using
765+
:attr:`default_factory`.
766+
767+
A direct call to this method (meaning a call that isn't coming from
768+
:meth:`__getitem__`) can create a :term:`race condition`. To reset an
769+
item to a default value the next time it's accessed, use the
770+
:meth:`~dict.pop` method to safely remove the current value.
772771

773772

774773
:class:`defaultdict` objects support the following instance variable:

0 commit comments

Comments
 (0)