Skip to content

erroneous complaint during tree walk #18608

Closed as not planned
Closed as not planned

Description

@cjw296

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

Activity

  1. hauntsaninja commented on Feb 5, 2025

    @hauntsaninja
    Collaborator

    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)
    
  2. ilevkivskyi commented on Feb 5, 2025

    @ilevkivskyi
    Member

    Yes, a duplicate of #2008

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions