python / python/mypy

Assignability of overloaded implementation to `Proto[**P](Protocol)` is overload-order-sensitive

Offen
#19,480 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-protocols
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report, To Reproduce & Actual Behaviour

When matching a method signature in a protocol with an overloaded implementation, the implementation's overload order appears to matter, even when only one of the overloads match.

In the following example, only the first overload of the implementation is tried for compatibility with the protocol (which looks similar to the issue in #14070). See mypy Playground:

# mypy: disable-error-code=no-overload-impl

from typing import *

_A_contra = TypeVar("_A_contra", bound=Literal["a", "b"], contravariant=True)
_P = ParamSpec("_P")

class Callback(Protocol[_A_contra, _P]):
    def method(self, a: _A_contra, *args: _P.args, **kwargs: _P.kwargs) -> None: ...
    
class Impl:
    @overload
    def method(self, a: Literal["a"], b: int) -> None: ...
    @overload
    def method(self, a: int, b: str) -> None: ...

class Impl2:  # Overload signature order is reversed compared with `Impl`
    @overload
    def method(self, a: int, b: str) -> None: ...
    @overload
    def method(self, a: Literal["a"], b: int) -> None: ...

def accepts_callback(cb: Callback[Literal["a"], _P], *args: _P.args, **kwargs: _P.kwargs) -> int: 
    return 1

a = accepts_callback(Impl(), 1)
b = accepts_callback(Impl2(), 1)  # Error
reveal_type(a)
reveal_type(b)

Expected Behavior

No errors

Your Environment

  • Mypy version used: 1.16.1, master
  • Python version used: 3.12

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit dem bereitgestellten Python 3.12-Reproduzierer im mypy Playground und vergleiche, wie Impl und Impl2 gegen Callback geprüft werden. Überprüfe das erwartete Ergebnis, indem du das Beispiel ausführst und prüfst, dass beide Aufrufe keinen Fehler erzeugen und die aufgedeckten Typen konsistent bleiben.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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