Skip to content

Fix false positive checking a class against type[Protocol] with instance attributes - #562

Merged
agronholm merged 4 commits into
agronholm:masterfrom
AnayGarodia:fix-protocol-class-instance-attrs
Jul 19, 2026
Merged

Fix false positive checking a class against type[Protocol] with instance attributes#562
agronholm merged 4 commits into
agronholm:masterfrom
AnayGarodia:fix-protocol-class-instance-attrs

Conversation

@AnayGarodia

Copy link
Copy Markdown
Contributor

Fixes #499

Checking a class (not an instance) against type[SomeProtocol] raised a false-positive TypeCheckError when the protocol declared a non-ClassVar attribute that the class sets in __init__:

class Proto(Protocol):
    foo: str

class Foo:
    def __init__(self) -> None:
        self.foo = "bar"

check_type(Foo, type[Proto])   # raised, though mypy/pyright accept it

Per PEP 544, an attribute annotation without ClassVar describes an instance attribute, so a class object is not expected to carry it. This implements the approach you outlined in the issue: when the subject is a class, check_protocol now ignores non-ClassVar attribute annotations and only requires the ClassVar ones to be present on the class. Instance checks are unchanged, and method/callable checks are untouched.

Added two regression tests: a class satisfying a protocol via an instance attribute no longer raises, and a class missing a required ClassVar member still does. The full tests/test_checkers.py suite passes.

Copilot AI review requested due to automatic review settings July 8, 2026 19:54

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coveralls

coveralls commented Jul 8, 2026

Copy link
Copy Markdown

Coverage Status

coverage: 94.855% (+0.008%) from 94.847% — AnayGarodia:fix-protocol-class-instance-attrs into agronholm:master

@agronholm
agronholm merged commit f1007ef into agronholm:master Jul 19, 2026
11 checks passed
@agronholm

Copy link
Copy Markdown
Owner

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Class is not compatible with protocol because it has no attribute named ...

4 participants