python / python/mypy

TypeGuard behavior does not match python semantics in async functions

Aperta
#19,608 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

I'm not sure if this should go here or in the mypyc issue tracker. I believe its a bug in mypy itself which only causes notable issues when you compile code with mypyc.

Bug Report

TypeGuard behavior does not match python semantics in async functions. The block which a TypeGuard applies to should end at the next await, assuming the TypeGuard is on an instance attribute or some other mutable nonlocal var.

This causes unnecessary TypeErrors in mypyc-compiled code.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=50cf9499e4e5be34d3faa754bd6052c0

Note: This code snippet does not produce any mypy errors, the bug is only exposed when compiling similar code with mypyc.

Expected Behavior

The TypeGuard should only guarantee the type of self._db up to the next await/async with/async for, because after that point the type is no longer guaranteed.

Actual Behavior

The TypeGuard "guarantees" the type of self._db longer than it is logically able to. Mypyc will raise a TypeError on line 12 if another task sets self._db while our coroutine waits for the lock.

Your Environment

  • Mypy version used: 1.17.0
  • Python version used: 3.12

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 riproduttore mypy-play collegato e confronta il narrowing di TypeGuard prima e dopo await, async with e async for. Traccia il comportamento pertinente del controllo dei tipi di async-function e aggiungi una copertura di regressione che dimostri che un valore mutable nonlocal non viene ristretto oltre il punto di sospensione; il lavoro è terminato quando mypyc non incontra più il TypeError segnalato.

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
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.