8000 bpo-42059: Fix required/optional keys for TypedDict(..., total=False)… · python/cpython@dbb0006 · GitHub
[go: up one dir, main page]

Skip to content

Commit dbb0006

Browse files
bpo-42059: Fix required/optional keys for TypedDict(..., total=False) (GH-22736) (GH-23747)
(cherry picked from commit 67b769f) Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>
1 parent 20bc40e commit dbb0006

File tree

3 files changed

+7
-2
lines changed

3 files changed

+7
-2
lines changed

Lib/test/test_typing.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3891,10 +3891,14 @@ def test_total(self):
38913891
self.assertEqual(D(), {})
38923892
self.assertEqual(D(x=1), {'x': 1})
38933893
self.assertEqual(D.__total__, False)
3894+
self.assertEqual(D.__required_keys__, frozenset())
3895+
self.assertEqual(D.__optional_keys__, {'x'})
38943896

38953897
self.assertEqual(Options(), {})
38963898
self.assertEqual(Options(log_level=2), {'log_level': 2})
38973899
self.assertEqual(Options.__total__, False)
3900+
self.assertEqual(Options.__required_keys__, frozenset())
3901+
self.assertEqual(Options.__optional_keys__, {'log_level', 'log_path'})
38983902

38993903
def test_optional_keys(self):
39003904
class Point2Dor3D(Point2D, total=False):

Lib/typing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1987,14 +1987,14 @@ class body be required.
19871987
raise TypeError("TypedDict takes either a dict or keyword arguments,"
19881988
" but not both")
19891989

1990-
ns = {'__annotations__': dict(fields), '__total__': total}
1990+
ns = {'__annotations__': dict(fields)}
19911991
try:
19921992
# Setting correct module is necessary to make typed dict classes pickleable.
19931993
ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
19941994
except (AttributeError, ValueError):
19951995
pass
19961996

1997-
return _TypedDictMeta(typename, (), ns)
1997+
return _TypedDictMeta(typename, (), ns, total=total)
19981998

19991999
_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
20002000
TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:class:`typing.TypedDict` types created using the alternative call-style syntax now correctly respect the ``total`` keyword argument when setting their ``__required_keys__`` and ``__optional_keys__`` class attributes.

0 commit comments

Comments
 (0)
0