Constrained `TypeVar` causes issues in type narrowing in attributes
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
A constrained typing.TypeVar object's attributes does not appear to type-narrow properly.
To Reproduce & Actual Behaviour
In the following example, an AST node transformation is trying to unravel the contents of an if typing.TYPE_CHECKING block into the owning namespace:
import ast
from typing import TypeVar
NamespaceNodeT = TypeVar("NamespaceNodeT", ast.Module, ast.ClassDef)
def unravel_TYPE_CHECKING(node: NamespaceNodeT) -> None:
body_stmt: ast.stmt
for body_stmt in list(node.body):
if isinstance(body_stmt, ast.If) and (
"TYPE_CHECKING" in ast.unparse(body_stmt.test)
):
reveal_type(body_stmt) # note: Revealed type is "_ast.If"
reveal_type(body_stmt.body) # note: Revealed type is "builtins.list[_ast.stmt]"
if_idx: int = node.body.index(body_stmt)
node.body[:] = [
*node.body[:if_idx],
*body_stmt.body, # error: "stmt" has no attribute "body" [attr-defined]
*body_stmt.orelse, # error: "stmt" has no attribute "orelse" [attr-defined]
*node.body[if_idx + 1 :],
]
The reveal_type lines see body_stmt as properly type-narrowed, but something else causes an issue when trying to use body_stmt's attributes?
Expected Behavior
I expected node: NamespaceNodeT to behave the same as node: ast.Module | ast.ClassDef, which causes no issues.
Your Environment
- Mypy version used: 0.991 and master
- Mypy command-line flags: (default)
- Mypy configuration options from
mypy.ini(and other config files): (default) - Python version used: 3.10
See mypy-play example.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo il riproduttore fornito in mypy-play con mypy master, quindi confronta l’annotazione del TypeVar vincolato con la versione ast.Module | ast.ClassDef. Traccia come viene preservato il restringimento del tipo per l’accesso agli attributi di body_stmt; il lavoro è completato quando il caso del TypeVar vincolato accetta body_stmt.body e body_stmt.orelse senza errori.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100