Skip to content

erroneous complaint during tree walk #18608

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
cjw296 opened this issue Feb 5, 2025 · 2 comments
Closed

erroneous complaint during tree walk #18608

cjw296 opened this issue Feb 5, 2025 · 2 comments
Labels
bug mypy got something wrong

Comments

@cjw296
Copy link

cjw296 commented Feb 5, 2025

Bug Report

@hauntsaninja suggested I raise this.

To Reproduce

from dataclasses import dataclass
from typing import TypeVar, Generic, Any

T = TypeVar('T')

@dataclass()
class Element(Generic[T]):
    value: T
    parent: "Element[Any] | None" = None


    def walk(self) -> None:
        current: Element[Any] | None = self
        while current := current.parent:
            print(current.value)

Expected Behavior

$ pyright --version
pyright 1.1.393
$ pyright type_bug.py 
0 errors, 0 warnings, 0 informations 

Actual Behavior

$ mypy --version
mypy 1.14.1 (compiled: yes)
$ mypy type_bug.py 
type_bug.py:14: error: Item "None" of "Element[Any] | None" has no attribute "parent"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.14.1
  • Python version used: Python 3.12.1
@cjw296 cjw296 added the bug mypy got something wrong label Feb 5, 2025
@hauntsaninja
Copy link
Collaborator

hauntsaninja commented Feb 5, 2025

Thanks for filing. Looking at this, I think it's just a (slightly confusing) duplicate of #2008. Old issue, but we've recently made progress towards it. Last I checked the primer for the fix was starting to look not too bad (see hauntsaninja#4)

One way to work around is to move the assignment to a separate line from the annotation:

current: Element | None
current = self

See also:

from __future__ import annotations
from typing import Any

class Element:
    value: int
    parent: Element | None

    def walk(self) -> None:
        current: Element | None
        current = self
        while current := current.parent:
            print(current.value)

@ilevkivskyi
Copy link
Member

Yes, a duplicate of #2008

@ilevkivskyi ilevkivskyi closed this as not planned Won't fix, can't repro, duplicate, stale Feb 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants