Cannot determine type of attribute due to circular reference:
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Is this a bug?
The following code (playground link)...
class X:
def __init__(self, value: str | None = None, parent: X | None = None) -> None:
if value is None:
if parent is not None and parent.value is not None:
value = "something"
else:
value = "something_else"
reveal_type(value)
self.value = value
Produces this output...
main.py:4: error: Cannot determine type of "value"
main.py:8: note: Revealed type is "builtins.str"
Here, it's clear that the type of X.value is a string, as indicated by reveal_type, but MyPy is unable to realize this by the time we reach parent.value.
The solution is to forward declare the type of X.value:
class X:
def __init__(self, value: str | None = None, parent: X | None = None) -> None:
self.value: str
if value is None:
if parent is not None and parent.value is not None:
value = "something"
else:
value = "something_else"
self.value = value
But that doesn't seem necessary given that resolving the circular reference is not strictly required to figure out what the type of X.value is.
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 mit dem verlinkten mypy playground und reproduziere das Beispiel unter mypy 0.910, Python 3.10 und dem strict mode. Verfolge die Inferenz rund um parent.value und self.value im relevanten Type-Checking-Pfad. Fertig ist die Aufgabe, wenn das Beispiel nicht mehr meldet, dass der Typ von value nicht bestimmt werden kann, während der aufgedeckte Typ str erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100