python / python/mypy

Cannot determine type of attribute due to circular reference:

Open
#10,749 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

question topic-recursive-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

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 = 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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked mypy playground and reproduce the example under mypy 0.910, Python 3.10, and strict mode. Trace the inference around parent.value and self.value in the relevant type-checking path. Done means the example no longer reports that value's type cannot be determined while retaining the revealed str type.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.