Skip to content

Use dummy concrete type instead of Any when checking protocol variance - #20110

Merged
ilevkivskyi merged 1 commit into
python:masterfrom
bzoracler:fix-20108
Oct 27, 2025
Merged

Use dummy concrete type instead of Any when checking protocol variance#20110
ilevkivskyi merged 1 commit into
python:masterfrom
bzoracler:fix-20108

Conversation

@bzoracler

@bzoracler bzoracler commented Oct 24, 2025

Copy link
Copy Markdown
Contributor

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
Copy Markdown
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

@sterliakov sterliakov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Makes sense, thanks!

@ilevkivskyi
ilevkivskyi merged commit 31a915a into python:master Oct 27, 2025
20 checks passed
@bzoracler
bzoracler deleted the fix-20108 branch October 27, 2025 18:15
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

3 participants