python / python/mypy

mypy reports `used-before-def` with `TypeAlias`es despite `from __future__ import annotations`

Aperta
#14,539 10 commenti 2 reazioni 1 assegnatario Vedi su GitHub

@ilinum ci sta già lavorando.

Dal 27/1/2023.

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

Descrizione

Bug Report

from __future__ import annotations helps avoid NameErrors with later-defined entities in python, but seems to ineffective with use(d)-before-def in mypy.

To Reproduce (edited example code, see edit history for previous version if I mis-edited anything):

"""Bug."""
from __future__ import annotations
from typing import TYPE_CHECKING

# This works (only) with `from __future__ import annotations`:
list_direct: list[Class] = []

# By contrast, mypy reports `used-before-def` either way:
if TYPE_CHECKING:
    ListOfClass = list[Class]
list_via_alias: ListOfClass = []

class Class:
    pass

Expected Behavior

No error

Actual Behavior

bug.py:8: error: Name "MyClass" is used before definition [used-before-def]

Your Environment

  • Mypy version used: mypy 1.0.0+dev.425fb0b4cfaa78cd0bf23fd165e4d6a1170670fe (compiled: no)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.1

Related: https://github.com/python/mypy/pull/14163, https://github.com/python/mypy/pull/14166

Interestingly, no error on playground on master:
https://mypy-play.net/?mypy=master&python=3.11&gist=f323516535c0d04cf4e0a2f2c985f4ff

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.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.