From 3f1daea6489882bb4c55f178014c72c35f596e2e Mon Sep 17 00:00:00 2001 From: Max Bernstein Date: Thu, 20 Mar 2025 00:10:26 -0400 Subject: [PATCH 1/2] Clarify defaultdict keyword argument behavior in docs --- Doc/library/collections.rst | 4 ++++ Modules/_collectionsmodule.c | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 5fbdb12f40cafa..4789d04a2aab54 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -727,6 +727,10 @@ stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, as if they were passed to the :class:`dict` constructor, including keyword arguments. + Note that this means ``defaultdict(default_factory=list)`` (for example), + will create a dict with a key of ``'default_factory'`` and a value of + :class:`list`. Instead, call ``defaultdict(list)``. + :class:`defaultdict` objects support the following method in addition to the standard :class:`dict` operations: diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c index ad670293ec5b6a..8b59d9f4a35a51 100644 --- a/Modules/_collectionsmodule.c +++ b/Modules/_collectionsmodule.c @@ -2476,6 +2476,10 @@ a new value when a key is not present, in __getitem__ only.\n\ A defaultdict compares equal to a dict with the same items.\n\ All remaining arguments are treated the same as if they were\n\ passed to the dict constructor, including keyword arguments.\n\ +\n\ +Note that this means defaultdict(default_factory=list) (for\n\ +example), will create a dict with a key of 'default_factory'\n\ +and a value of . Instead, call defaultdict(list).\n\ "); /* See comment in xxsubtype.c */ From 97972f69263fef39ec680dfe39cae90903f3fee1 Mon Sep 17 00:00:00 2001 From: Max Bernstein Date: Thu, 20 Mar 2025 00:17:34 -0400 Subject: [PATCH 2/2] Add doctest --- Doc/library/collections.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 4789d04a2aab54..689c380ca6e3f8 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -731,6 +731,11 @@ stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, will create a dict with a key of ``'default_factory'`` and a value of :class:`list`. Instead, call ``defaultdict(list)``. + >>> defaultdict(default_factory=list) + defaultdict(None, {'default_factory': }) + >>> defaultdict(list) + defaultdict(, {}) + >>> :class:`defaultdict` objects support the following method in addition to the standard :class:`dict` operations: