False negative when declaring a class with a literal string base, which could refer to a forward-reference type alias
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
mypy interprets a literal string, which could refer to a forward-reference type alias, as a valid class base.
To Reproduce
The following example uses both a forward reference (class B1("A")) and a string which doesn't refer to anything (class B2("D")):
class B1("A"):
pass
b1: B1 = B1()
b1.a = "" # mypy: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
class B2("D"): # mypy: Class cannot subclass value of type "Any" [misc] \
# mypy: Name "D" is not defined [name-defined]
pass
class A:
a: int
Expected Behavior
I expect the following snippet to show up if we're not under a typing.TYPE_CHECKING block:
class B1("A"): # mypy: Invalid base class "A" [misc] \
# mypy: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases \
# mypy: Variable "A" is not valid as a type [valid-type]
pass
EDIT: this is a more sensible expected error:
class B1("A"): # mypy: Invalid base class [misc]
pass
I can't gauge from PEP 613 whether or not this should should be OK (mypy doesn't show any errors, but FWIW pylance or pyright sees this as an error):
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
class B("A"): # pylance: Expected class type but received "Literal['A']" \
# pylance: Base class type is unknown, obscuring type of derived class
pass
class A:
pass
Your Environment
Tested on mypy-play.net:
- Mypy version used: 0.981 and
master - Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files):show_error_codes = True - Python version used: 3.10
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, die beiden Beispiele für Klassenbasen auf mypy-play.net mit mypy 0.981 oder master und ohne Befehlszeilen-Flags nachzustellen. Vergleiche die Diagnosen für die Vorwärtsreferenz und die nicht auflösbaren Literal-String-Basen und ermittle dann das beabsichtigte Verhalten außerhalb und innerhalb von TYPE_CHECKING; fertig ist es, wenn die relevanten Fälle den vereinbarten Fehler für eine ungültige Basis melden, ohne gültige Vorwärtsreferenzen zu beeinträchtigen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100