python / python/typing

Request: an AssertingTypeGuard type for TypeGuard-like semantics

Aperta
#930 6 commenti 28 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

topic: feature
Lingua principale
Python
Stelle
1.8k
Fork
302
Merge medio
23h
PR unite (30g)
8

Descrizione

There is a frequent pattern of TypeGuard-like functions which assert or otherwise raise an exception if a type constraint is not met.

For example, https://github.com/microsoft/pyright/issues/2007 points to a case in which unittest provides assertIsNotNone, but a type-checker cannot infer that type narrowing has occurred. Arguably, the popular typeguard library is based around an implementation of "asserting" type guards. (One which deduces what assertions should be made from the annotations.)

TypeGuards allow for semantics like

y: str
assert is_list_of_str(x)
assert len(x) > 0
y = x[0]

An AssertingTypeGuard would allow for

y: str
assert_is_nonempty_list_of_str(x)  # note, this encodes another runtime check, the len check
y = x[0]

This becomes especially valuable if we consider that you might not want to do this all with assert. I may, as an author, prefer my own custom exceptions, e.g.

def assert_is_nonempty_list_of_str(x) -> AssertingTypeGuard[list[str]]:
    if not isinstance(x, list):
        raise ExpectedListError(x)
    if not x:
        raise EmptyContainerError(x)
    if not all(isinstance(y, str) for y in x):
        raise ContainedInvalidTypeError(x, str)
    return x

(Apologies if this repo is the wrong place to submit this request/idea. I'm happy to go through another process if necessary.)

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

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

La richiesta non identifica file di implementazione né test. Inizia esaminando gli esempi di TypeGuard, la issue collegata di Pyright e la discussione sulla libreria typeguard; determina se un AssertingTypeGuard appartenga alla specifica di typing e definisci la semantica attesa del narrowing e delle eccezioni prima dell’implementazione.

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

Valutazione

Stack tecnologico
python
Ambito
developer-experience
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Tranquilla
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.