Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5757,6 +5757,13 @@ Frozen dictionaries
Like dictionaries, frozendicts are :ref:`generic <generics>` over two types,
signifying (respectively) the types of the frozendict's keys and values.

.. classmethod:: fromkeys(iterable, value=None, /)

Similar to :meth:`dict.fromkeys`, but call again the type constructor
with an initialized :class:`frozendict` if the type is a
:class:`frozendict` subclass or if the constructor returned a
:class:`frozendict`.

.. versionadded:: 3.15


Expand Down
31 changes: 19 additions & 12 deletions Lib/test/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -1939,8 +1939,11 @@ def test_fromkeys(self):
# Subclass which overrides the constructor
created = frozendict(x=1)
class FrozenDictSubclass(frozendict):
def __new__(self):
return created
def __new__(cls, *args, **kwargs):
if args or kwargs:
return super().__new__(cls, *args, **kwargs)
else:
return created

fd = FrozenDictSubclass.fromkeys("abc")
self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None))
Expand All @@ -1952,6 +1955,20 @@ def __new__(self):
self.assertEqual(type(fd), FrozenDictSubclass)
self.assertEqual(created, frozendict(x=1))

# Dict subclass with a constructor which returns a frozendict
# by default
class DictSubclass(dict):
def __new__(cls, *args, **kwargs):
if args or kwargs:
return super().__new__(cls, *args, **kwargs)
else:
return created

fd = DictSubclass.fromkeys("abc")
self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None))
self.assertEqual(type(fd), DictSubclass)
self.assertEqual(created, frozendict(x=1))

# Subclass which doesn't override the constructor
class FrozenDictSubclass2(frozendict):
pass
Expand All @@ -1960,16 +1977,6 @@ class FrozenDictSubclass2(frozendict):
self.assertEqual(fd, frozendict(a=None, b=None, c=None))
self.assertEqual(type(fd), FrozenDictSubclass2)

# Dict subclass which overrides the constructor
class DictSubclass(dict):
def __new__(self):
return created

fd = DictSubclass.fromkeys("abc")
self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None))
self.assertEqual(type(fd), DictSubclass)
self.assertEqual(created, frozendict(x=1))

def test_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
for fd in (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:meth:`!frozendict.fromkeys` now only tracks the :class:`frozendict` in the
garbage collector once the dictionary is fully initialized. Patch by Donghee Na
and Victor Stinner.
Loading
Loading