-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Open
Description
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 = valueProduces 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 = valueBut 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.
amarshall