Skip to content

Add note explaining Container[T] __contains__ parameter rules#20741

Open
KarthickKrishnasaisha wants to merge 2 commits intopython:masterfrom
KarthickKrishnasaisha:clarify-container-contains
Open

Add note explaining Container[T] __contains__ parameter rules#20741
KarthickKrishnasaisha wants to merge 2 commits intopython:masterfrom
KarthickKrishnasaisha:clarify-container-contains

Conversation

@KarthickKrishnasaisha
Copy link

This PR clarifies a common point of confusion around Container[T] and the
required signature of contains.

Container[T] does not restrict the argument type of contains, which
must accept object to remain substitutable. The type parameter T is used
for membership checks and narrowing, not for the method signature.

The change adds a short explanatory note to the protocol mismatch
diagnostic and includes a regression test covering this case.

Fixes #20740

@github-actions

This comment has been minimized.

Copy link
Collaborator

@A5rocks A5rocks left a comment

Choose a reason for hiding this comment

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

I don't think this is actually a common misunderstanding.

def __contains__(self, item: str) -> bool:
return True

c: Container[str] = StringContainer()
Copy link
Collaborator

Choose a reason for hiding this comment

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

This test seems incomplete?

@github-actions
Copy link
Contributor

github-actions bot commented Feb 5, 2026

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

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.

__contains__ must accept object even when container is annotated as Container[str]

2 participants