Skip to content

Cannot determine type of attribute due to circular reference: #10749

Open
@rmorshea

Description

@rmorshea

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions