8000 [3.9] bpo-42059: Fix required/optional keys for TypedDict(..., total=False) (GH-22736) by miss-islington · Pull Request #23747 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

[3.9] bpo-42059: Fix required/optional keys for TypedDict(..., total=False) (GH-22736) #23747

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 14, 2020
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
4 changes: 4 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3899,10 +3899,14 @@ def test_total(self):
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):
Expand Down
4 changes: 2 additions & 2 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1980,14 +1980,14 @@ class body be required.
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,)
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
0