Skip to content
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
2 changes: 1 addition & 1 deletion mypy/plugins/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def typed_dict_pop_callback(ctx: MethodContext) -> Type:

value_types = []
for key in keys:
if key in ctx.type.required_keys:
if key in ctx.type.required_keys or key in ctx.type.readonly_keys:
ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, key_expr)

value_type = ctx.type.items.get(key)
Expand Down
6 changes: 5 additions & 1 deletion test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -3760,20 +3760,24 @@ del x["optional_key"] # E: Key "optional_key" of TypedDict "TP" cannot be delet
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyMutateMethods]
from typing import ReadOnly, TypedDict
from typing import ReadOnly, NotRequired, TypedDict

class TP(TypedDict):
key: ReadOnly[str]
optional_key: ReadOnly[NotRequired[str]]
other: ReadOnly[int]
mutable: bool

x: TP
reveal_type(x.pop("key")) # N: Revealed type is "builtins.str" \
# E: Key "key" of TypedDict "TP" cannot be deleted
reveal_type(x.pop("optional_key")) # N: Revealed type is "builtins.str" \
# E: Key "optional_key" of TypedDict "TP" cannot be deleted


x.update({"key": "abc", "other": 1, "mutable": True}) # E: ReadOnly TypedDict keys ("key", "other") TypedDict are mutated
x.setdefault("key", "abc") # E: ReadOnly TypedDict key "key" TypedDict is mutated
x.setdefault("optional_key", "foo") # E: ReadOnly TypedDict key "optional_key" TypedDict is mutated
x.setdefault("other", 1) # E: ReadOnly TypedDict key "other" TypedDict is mutated
x.setdefault("mutable", False) # ok
[builtins fixtures/dict.pyi]
Expand Down