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
4 changes: 4 additions & 0 deletions mypy/checker_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,10 @@ def checking_await_set(self) -> Iterator[None]:
def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None:
raise NotImplementedError

@abstractmethod
def add_any_attribute_to_type(self, typ: Type, name: str) -> Type:
raise NotImplementedError

@abstractmethod
def is_defined_in_stub(self, typ: Instance, /) -> bool:
raise NotImplementedError
Expand Down
15 changes: 9 additions & 6 deletions mypy/checkpattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,12 +671,15 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType:
has_local_errors = local_errors.has_new_errors()
if has_local_errors or key_type is None:
key_type = AnyType(TypeOfAny.from_error)
self.msg.fail(
message_registry.CLASS_PATTERN_UNKNOWN_KEYWORD.format(
typ.str_with_options(self.options), keyword
),
pattern,
)
if not (type_info and type_info.fullname == "builtins.object"):
self.msg.fail(
message_registry.CLASS_PATTERN_UNKNOWN_KEYWORD.format(
typ.str_with_options(self.options), keyword
),
pattern,
)
elif keyword is not None:
new_type = self.chk.add_any_attribute_to_type(new_type, keyword)

inner_type, inner_rest_type, inner_captures = self.accept(pattern, key_type)
if is_uninhabited(inner_type):
Expand Down
9 changes: 9 additions & 0 deletions test-data/unit/check-python310.test
Original file line number Diff line number Diff line change
Expand Up @@ -1002,15 +1002,24 @@ match m:
[builtins fixtures/tuple.pyi]

[case testMatchClassPatternNonexistentKeyword]
from typing import Any
class A: ...

m: object
n: Any

match m:
case A(a=j): # E: Class "__main__.A" has no attribute "a"
reveal_type(m) # N: Revealed type is "__main__.A"
reveal_type(j) # N: Revealed type is "Any"

match n:
# Matching against object should not emit an error for non-existing keys
case object(a=k):
reveal_type(n) # N: Revealed type is "builtins.object"
reveal_type(n.a) # N: Revealed type is "Any"
reveal_type(k) # N: Revealed type is "Any"

[case testMatchClassPatternDuplicateKeyword]
class A:
a: str
Expand Down
Loading