python / python/mypy

Should `*args` narrow in type guards?

Aperta
#14,273 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-typeguard-typeis
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con il TODO TypeGuard *args citato nell’issue e confronta il comportamento di mypy con il testo di PEP 647 e l’esempio Pyright collegato. Determina se il narrowing debba essere applicato al primo argomento *args, a tutti gli argomenti o a nessuno; il lavoro è completato quando il progetto ha deciso il comportamento e il TODO è stato risolto di conseguenza.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.