Skip to content

Commit 87998c8

Browse files
Allow TypedDict assignment of Required item to NotRequired ReadOnly item (#18164)
Fixes #18162
1 parent 11c58a7 commit 87998c8

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

Diff for: mypy/subtypes.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -910,14 +910,12 @@ def visit_typeddict_type(self, left: TypedDictType) -> bool:
910910
return False
911911
# Non-required key is not compatible with a required key since
912912
# indexing may fail unexpectedly if a required key is missing.
913-
# Required key is not compatible with a non-required key since
914-
# the prior doesn't support 'del' but the latter should support
915-
# it.
916-
#
917-
# NOTE: 'del' support is currently not implemented (#3550). We
918-
# don't want to have to change subtyping after 'del' support
919-
# lands so here we are anticipating that change.
920-
if (name in left.required_keys) != (name in right.required_keys):
913+
# Required key is not compatible with a non-read-only non-required
914+
# key since the prior doesn't support 'del' but the latter should
915+
# support it.
916+
# Required key is compatible with a read-only non-required key.
917+
required_differ = (name in left.required_keys) != (name in right.required_keys)
918+
if not right_readonly and required_differ:
921919
return False
922920
# Readonly fields check:
923921
#

Diff for: test-data/unit/check-typeddict.test

+14
Original file line numberDiff line numberDiff line change
@@ -3894,6 +3894,20 @@ accepts_B(b)
38943894
[builtins fixtures/dict.pyi]
38953895
[typing fixtures/typing-typeddict.pyi]
38963896

3897+
[case testTypedDictRequiredConsistentWithNotRequiredReadOnly]
3898+
from typing import NotRequired, ReadOnly, Required, TypedDict
3899+
3900+
class A(TypedDict):
3901+
x: NotRequired[ReadOnly[str]]
3902+
3903+
class B(TypedDict):
3904+
x: Required[str]
3905+
3906+
def f(b: B):
3907+
a: A = b # ok
3908+
[builtins fixtures/dict.pyi]
3909+
[typing fixtures/typing-typeddict.pyi]
3910+
38973911
[case testTypedDictReadOnlyCall]
38983912
from typing import ReadOnly, TypedDict
38993913

0 commit comments

Comments
 (0)