python / python/mypy

Document how to declare dependant types in method signatures

Offen
#8,662 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

documentation topic-type-variables
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

I have several TypedDict:

TerminateHandlerContextType = TypedDict( "TerminateHandlerContextType",{...},)
CrashHandlerContextType = TypedDict( "CrashHandlerContextType", {... },)
QuitHandlerContextType = TypedDict("QuitHandlerContextType", {...})

And then related Callable:

TerminateHandlerType = Callable[[TerminateHandlerContextType], None]
QuitHandlerType = Callable[[QuitHandlerContextType], None]
CrashHandlerType = Callable[[CrashHandlerContextType], None]

If I then declare a method that depends of both:

    def _call_handler(
    self,
    handler: Union[
        TerminateHandlerType, QuitHandlerType, CrashHandlerType
    ],
    context: Union[
         TerminateHandlerContextType, QuitHandlerContextType, CrashHandlerContextType,
    ],
    ):
        ...
        return handler(context) # <---- MYPY COMPLAINS HERE

Then mypy complains, because, while I always ensure logically that the proper handler is called with the proper context, it can't see that.

I couldn't find in the documentation a way to tell it that the context type depends on the handler type. I assume it's either a Generic, or a TypeVar, but didn't find the solution.


mypy 0.770
python 3.6

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

In der Issue wird keine Dokumentationsdatei, kein Test und kein Einstiegspunkt genannt. Bestimme zunächst, welcher Abschnitt der mypy-Dokumentation abhängige Beziehungen zwischen Handler- und Kontexttypen behandelt, und überprüfe dann den dokumentierten Ansatz anhand des TypedDict- und Callable-Beispiels. Als erledigt gilt die Aufgabe, wenn die Dokumentation erklärt, wie diese Beziehung ausgedrückt oder behandelt wird, und auf die gemeldete Beanstandung bei der Typprüfung eingeht.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Dokumentation
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

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