]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42059: Fix required/optional keys for TypedDict(..., total=False) (GH-22736)
authorAlex Grönholm <alex.gronholm@nextday.fi>
Thu, 10 Dec 2020 21:49:05 +0000 (23:49 +0200)
committerGitHub <noreply@github.com>
Thu, 10 Dec 2020 21:49:05 +0000 (13:49 -0800)
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2020-10-17-12-42-08.bpo-42059.ZGMZ3D.rst [new file with mode: 0644]

index 8ffc7f40cebdd275f49095120d9745c6e699cdd8..f3e38b6f47d1e1ae5036d239008f38eb5735941e 100644 (file)
@@ -3895,10 +3895,14 @@ class TypedDictTests(BaseTestCase):
         self.assertEqual(D(), {})
         self.assertEqual(D(x=1), {'x': 1})
         self.assertEqual(D.__total__, False)
+        self.assertEqual(D.__required_keys__, frozenset())
+        self.assertEqual(D.__optional_keys__, {'x'})
 
         self.assertEqual(Options(), {})
         self.assertEqual(Options(log_level=2), {'log_level': 2})
         self.assertEqual(Options.__total__, False)
+        self.assertEqual(Options.__required_keys__, frozenset())
+        self.assertEqual(Options.__optional_keys__, {'log_level', 'log_path'})
 
     def test_optional_keys(self):
         class Point2Dor3D(Point2D, total=False):
index 46c54c406992f748fa4b61ecfa75aea07a7400b6..148a505dad176ac708cf24102f1ecba522668b98 100644 (file)
@@ -2043,14 +2043,14 @@ def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
         raise TypeError("TypedDict takes either a dict or keyword arguments,"
                         " but not both")
 
-    ns = {'__annotations__': dict(fields), '__total__': total}
+    ns = {'__annotations__': dict(fields)}
     try:
         # Setting correct module is necessary to make typed dict classes pickleable.
         ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
     except (AttributeError, ValueError):
         pass
 
-    return _TypedDictMeta(typename, (), ns)
+    return _TypedDictMeta(typename, (), ns, total=total)
 
 _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
 TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
diff --git a/Misc/NEWS.d/next/Library/2020-10-17-12-42-08.bpo-42059.ZGMZ3D.rst b/Misc/NEWS.d/next/Library/2020-10-17-12-42-08.bpo-42059.ZGMZ3D.rst
new file mode 100644 (file)
index 0000000..3f18824
--- /dev/null
@@ -0,0 +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.