Skip to content

Conversation

@bzoracler
Copy link
Contributor

@bzoracler bzoracler commented Oct 24, 2025

Fixes #20108.

Variance checks for protocols follow a procedure roughly equivalent to that described in typing.python.org - Variance Inference. A major difference in mypy's current implementation is in Step 3:

Create two specialized versions of the class. We’ll refer to these as upper and lower specializations. In both of these specializations, replace all type parameters other than the one being inferred by a dummy type instance (a concrete anonymous class that is assumed to meet the bounds or constraints of the type parameter).

Mypy currently uses Any rather than a concrete dummy type. This causes issues during overload subtype checks in the example reported in the original issue, as the specialisations when checking variance suitability of _T2_contra look like:

from typing import TypeVar, Protocol, overload

_T1_contra = TypeVar("_T1_contra", contravariant=True)
_T2_contra = TypeVar("_T2_contra", contravariant=True)

class A(Protocol[<_T1_contra=Any>, _T2_contra]):
    @overload
    def method(self, a: <_T1_contra=Any>) -> None: ...
    @overload
    def method(self, a: _T2_contra) -> None: ...

This PR replaces the use of Any with a dummy concrete type in the entire protocol variance check to more closely follow the variance inference algorithm in the spec and fixes this overload issue.

@github-actions
Copy link
Contributor

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

@bzoracler bzoracler marked this pull request as ready for review October 24, 2025 02:29
Copy link
Collaborator

@sterliakov sterliakov left a comment

Choose a reason for hiding this comment

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

Makes sense, 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.

False positive with contravariant type variables in overloads implemented on Protocols

2 participants