Skip to content

Commit

Permalink
Allow TypedDict assignment of Required item to NotRequired ReadOnly i…
Browse files Browse the repository at this point in the history
…tem (#18164)

Fixes #18162
  • Loading branch information
brianschubert authored Nov 19, 2024
1 parent 11c58a7 commit 87998c8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
14 changes: 6 additions & 8 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -910,14 +910,12 @@ def visit_typeddict_type(self, left: TypedDictType) -> bool:
return False
# Non-required key is not compatible with a required key since
# indexing may fail unexpectedly if a required key is missing.
# Required key is not compatible with a non-required key since
# the prior doesn't support 'del' but the latter should support
# it.
#
# NOTE: 'del' support is currently not implemented (#3550). We
# don't want to have to change subtyping after 'del' support
# lands so here we are anticipating that change.
if (name in left.required_keys) != (name in right.required_keys):
# Required key is not compatible with a non-read-only non-required
# key since the prior doesn't support 'del' but the latter should
# support it.
# Required key is compatible with a read-only non-required key.
required_differ = (name in left.required_keys) != (name in right.required_keys)
if not right_readonly and required_differ:
return False
# Readonly fields check:
#
Expand Down
14 changes: 14 additions & 0 deletions test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -3894,6 +3894,20 @@ accepts_B(b)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictRequiredConsistentWithNotRequiredReadOnly]
from typing import NotRequired, ReadOnly, Required, TypedDict

class A(TypedDict):
x: NotRequired[ReadOnly[str]]

class B(TypedDict):
x: Required[str]

def f(b: B):
a: A = b # ok
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyCall]
from typing import ReadOnly, TypedDict

Expand Down

0 comments on commit 87998c8

Please sign in to comment.