A type can be consistent subtype of distinct materializations of a generic protocol

Offen
#20,193 2 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Anfängerfreundlichkeit
38/100
Issue-Typ
Bug
Klarheit
Größtenteils klar
Aktivitätsstatus
Veraltet
Tech-Stack
python
Bereich
compilers

Rechercherichtung

Führe die bereitgestellte Reproduktion mit mypy --strict aus und untersuche, wie die TypeIs-Eingrenzung die beiden generischen Protocol-Materialisierungen behandelt. Füge einen Regressionstest hinzu, der check1 und check2 abdeckt, und überprüfe anschließend, dass die inferierten Rückgabetypen und das Verhalten der Assertions den erwarteten Ergebnissen entsprechen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

bug topic-protocols

Bug Report

When using TypeIs to narrow a type down to two different fully static materializations of the same generic Protocol, MyPy will infer the result to be Never, thus producing false assertions.

To Reproduce

from typing import Any, Literal, Protocol, TypeIs

# ==== Basic definitions ====

class MockProtocol[T](Protocol):  # T is inferred to be contravariant
    def __call__(self, t: T) -> None:
        ...

class MockClass():
    def __call__(self, t: int | str) -> None:  # Implements MockProtocol[int | str]
        pass

# ==== Basic static type checking ====

def only_accept_mock_int(obj: MockProtocol[int]) -> None:
    pass

def only_accept_mock_str(obj: MockProtocol[str]) -> None:
    pass

only_accept_mock_int(MockClass())  # MockClass is subtype of MockProtocol[int]
only_accept_mock_str(MockClass())  # MockClass is subtype of MockProtocol[str]

# ==== Runtime type checking involving TypeIs ====

def is_mock_int(obj: Any) -> TypeIs[MockProtocol[int]]:
    return isinstance(obj, MockClass)  # Mock implementation

def is_mock_str(obj: Any) -> TypeIs[MockProtocol[str]]:
    return isinstance(obj, MockClass)  # Mock implementation

def check1(obj: MockClass) -> Literal[True]:  # Won't complain because `return False` is unreachable
    if is_mock_str(obj) and is_mock_int(obj):
        return True
    return False  # Inferred to be unreachable

def check2(obj: MockProtocol[str]) -> Literal[False]:  # Won't complain because `return True` is unreachable, which is incorrect!
    if is_mock_str(obj) and is_mock_int(obj):
        return True  # Inferred to be unreachable
    return False

result1 = check1(MockClass())  # Inferred to be Literal[True]
result2 = check2(MockClass())  # Inferred to be Literal[False], but the value is True!!!
assert result1 == result2  # Inferred to fail consistently, but it should succeed

Expected Behavior

check2 should be inferred as Callable[..., bool] because a fully static type can be subtype of both MockProtocol[str] and MockProtocol[int].

Actual Behavior

Literal[False] is recognized as a compatible return type of check2 due to false reachability assumption, causing the type of result2 to be wrong.

Your Environment

  • Mypy version used: 1.18.1
  • Mypy command-line flags: mypy --strict
  • Mypy configuration options from mypy.ini (and other config files): (default)
  • Python version used: Python 3.13.8
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
Ø Merge
1 T. 18 Std.
Gemergte PRs (30 T.)
54

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus python/mypy

Alle Issues in python/mypy

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.