Skip to content

Commit 67b769f

Browse files
authored
bpo-42059: Fix required/optional keys for TypedDict(..., total=False) (GH-22736)
1 parent a658287 commit 67b769f

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
@@ -3895,10 +3895,14 @@ def test_total(self):
38953895
self.assertEqual(D(), {})
38963896
self.assertEqual(D(x=1), {'x': 1})
38973897
self.assertEqual(D.__total__, False)
3898+
self.assertEqual(D.__required_keys__, frozenset())
3899+
self.assertEqual(D.__optional_keys__, {'x'})
38983900

38993901
self.assertEqual(Options(), {})
39003902
self.assertEqual(Options(log_level=2), {'log_level': 2})
39013903
self.assertEqual(Options.__total__, False)
3904+
self.assertEqual(Options.__required_keys__, frozenset())
3905+
self.assertEqual(Options.__optional_keys__, {'log_level', 'log_path'})
39023906

39033907
def test_optional_keys(self):
39043908
class Point2Dor3D(Point2D, total=False):

Lib/typing.py

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

2046-
ns = {'__annotations__': dict(fields), '__total__': total}
2046+
ns = {'__annotations__': dict(fields)}
20472047
try:
20482048
# Setting correct module is necessary to make typed dict classes pickleable.
20492049
ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
20502050
except (AttributeError, ValueError):
20512051
pass
20522052

2053-
return _TypedDictMeta(typename, (), ns)
2053+
return _TypedDictMeta(typename, (), ns, total=total)
20542054

20552055
_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
20562056
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)