python / python/mypy

Should `*args` narrow in type guards?

Offen
#14,273 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

While making a PR I found a TODO that goes along the lines of "is *args support for TypeGuard even worth it?"

I want to approach this from a different perspective. Pyright supports this:

from typing_extensions import TypeGuard

def typeguard(*args: object) -> TypeGuard[int]:
  ...

def f(x: object, y: object) -> None:
  if typeguard(x, y):
    reveal_type(x)  # revealed `int`
    reveal_type(y)  # revealed `object`

I'm ... not quite sure that should be allowed. Going strictly by the specification:

Type checkers should assume that type narrowing should be applied to the expression that is passed as the first positional argument to a user-defined type guard.

(PEP 647, emphasis my own)

Notice how it says first and argument (no s). (and the "passed as" sets up that we're talking about function signature, not how the function is called)


Anyways, given that:

  • other type checkers support it
  • but it doesn't seem widely used (there's been no issue on here AFAICT about it)
  • it's not part of the specification
  • it's not clear how it should extend (first *args argument (like pyright)? all of them (which would allow more flexibility)?)

Should this even be attempted in the first place? I'm in favor of removing the TODO.

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 im Issue referenzierten TypeGuard *args TODO und vergleiche das Verhalten von mypy mit dem Wortlaut von PEP 647 und dem verlinkten Pyright-Beispiel. Bestimme, ob die Eingrenzung auf das erste *args-Argument, auf alle Argumente oder auf keines angewendet werden sollte; abgeschlossen bedeutet, dass das Projekt ein festgelegtes Verhalten hat und das TODO entsprechend aufgelöst ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

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