From 369a4afc9f5eda263883f6b348b5f32fc9f4051c Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 16 May 2024 11:21:09 +0100 Subject: [PATCH] Fix variance inference when using real typeshed stubs --- mypy/subtypes.py | 6 +++--- test-data/unit/pythoneval.test | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 5aa6a08c0994..e1609717e160 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -1988,9 +1988,9 @@ def is_more_precise(left: Type, right: Type, *, ignore_promotions: bool = False) return is_proper_subtype(left, right, ignore_promotions=ignore_promotions) -def all_members(info: TypeInfo) -> set[str]: +def all_non_object_members(info: TypeInfo) -> set[str]: members = set(info.names) - for base in info.mro[1:]: + for base in info.mro[1:-1]: members.update(base.names) return members @@ -2012,7 +2012,7 @@ def infer_variance(info: TypeInfo, i: int) -> bool: contra = True tvar = info.defn.type_vars[i] self_type = fill_typevars(info) - for member in all_members(info): + for member in all_non_object_members(info): if member in ("__init__", "__new__"): continue node = info[member].node diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index b51a965c95da..0ed3540b6bb9 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -2091,3 +2091,24 @@ def f(d: Description) -> None: reveal_type(d.name_fn) [out] _testDataclassStrictOptionalAlwaysSet.py:9: note: Revealed type is "def (Union[builtins.int, None]) -> Union[builtins.str, None]" + +[case testPEP695VarianceInference] +# flags: --python-version=3.12 --enable-incomplete-feature=NewGenericSyntax +from typing import Callable, Final + +class Job[_R_co]: + def __init__(self, target: Callable[[], _R_co]) -> None: + self.target: Final = target + +def func( + action: Job[int | None], + a1: Job[int | None], + a2: Job[int], + a3: Job[None], +) -> None: + action = a1 + action = a2 + action = a3 + a2 = action # Error +[out] +_testPEP695VarianceInference.py:17: error: Incompatible types in assignment (expression has type "Job[None]", variable has type "Job[int]")