python / python/mypy

Maybe add semantical understanding of `assert not TYPE_CHECKING` (similar to `if not TYPE_CHECKING`)?

Aperta
#16,911 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Background
I'm using a helper type definition from a stubs package in project. I'll call it MyHelperType here (if it matters, it's actually StrOrPromise from django-stubs). We have two deployment settings:

  • In development settings, the stubs package is installed. Here, we'd like to always use its definition of MyHelperType (for mypy, and typeguard runtime checks during tests and usage)
  • In a production setting, we don't want to require the stubs package, so we just want MyHelperType to be anything that doesn't cause syntax errors, probably a type alias of Any.

I expected this snippet of code work:

from typing import TYPE_CHECKING, Any

try:
    # Helper Type import that may fail in production settings, abusing collections.abc.Sequence for this example
    from collections.abc import Sequence as MyHelperType
except ImportError:
    assert not TYPE_CHECKING
    MyHelperType = Any

but mypy will give these errors:

main.py:8: error: Cannot assign to a type  [misc]
main.py:8: error: Incompatible types in assignment (expression has type "object", variable has type "type[Sequence[Any]]")  [assignment]

I would have assumed that assert not TYPE_CHECKING causes mypy to treat the except-block as if it was guarded by if not TYPE_CHECKING -- mypy does not give errors for this example:

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    # Helper Type import that may fail in production settings, abusing collections.abc.Sequence for this example
    from collections.abc import Sequence as MyHelperType
else:
    MyHelperType = Any

However, this wouldn't give us run-time type checking provided by typeguard.

The current workaround for me is this more verbose/wet approach:

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from collections.abc import Sequence as MyHelperType
else:
    try:
        from collections.abc import Sequence as MyHelperType
    except ImportError:
        MyHelperType = Any

I may be missing background information or conclusions of past discussions, but to me it seems reasonable for mypy to understand assert not TYPE_CHECKING and treat the block / following statements as if they were guarded by if not TYPE_CHECKING. (I can see that this could be undesirable in other contexts, and that it may be disputable what should happen in case mypy cannot resolve the import.)

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

Riproduci i due esempi e l'attuale soluzione alternativa nei casi collegati di mypy-play, quindi traccia il modo in cui mypy gestisce le guardie TYPE_CHECKING e le istruzioni assert. Definisci il comportamento desiderato per assert not TYPE_CHECKING, inclusa la verifica delle assegnazioni, e aggiungi una copertura che mostri che il pattern proposto funziona senza modificare la semantica ordinaria di assert.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Funzionalità
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.