python / python/mypy

Field initialization in dataclasses is not correct propagated

Open
#16,810 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy should consider how the fields of a dataclass is initialized by the default constructor.

To Reproduce

from __future__ import annotations
from dataclasses import dataclass

@dataclass
class Node:
    item: int
    next: Node | None

p = Node(1, Node(2, None))

print(p.next.item)

Expected Behavior

mypy should consider the code valid.

Actual Behavior

It generates a error:

x.py:11: error: Item "None" of "Node | None" has no attribute "item"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Note that the following code is considered valid by mypy:

p = Node(1, None)
p.next = Node(2, Node)
print(p.next.item)

Your Environment

  • Mypy version used: 1.8

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 x.py reproducer and inspect how mypy analyzes dataclass-generated constructors and field initialization. The work is done when the shown Node example is accepted without the union-attr error, while the existing None-handling behavior remains correct.

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
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.