python / python/mypy

Mypy 1.7.0 makes two incorrect inferences about dataclass descriptor-based fields

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

Nobody has claimed this yet.

bug topic-dataclasses topic-descriptors
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When a dataclass field uses a descriptor, Mypy makes two incorrect inferences:

  1. If the descriptor has no default value (it raises AttributeError when accessed on the class), mypy incorrectly assumes it has a default and raises an error on the next field with no default value. The no-default mechanism was documented in Python 3.10 but has been there since 3.7. The specific code is in dataclasses._get_field, as default = getattr(cls, a_name, MISSING).
  2. If the descriptor-based field is typed with InitVar, mypy incorrectly assumes the attribute does not exist on the class.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=8a47d8538f2fc798a8564d30dae6434e

Expected Behavior

No error, matching runtime behaviour and the internal validations of the @dataclass decorator.

Actual Behavior

Two incorrect errors:

  1. Attributes without a default cannot follow attributes with one [misc]
  2. "Example2" has no attribute "this_exists" [attr-defined]

Your Environment

  • Mypy version used: 1.7.0 and 1.6.1
  • Python version used: 3.9 and 3.11

Related: #13856 describes another dataclass descriptor bug, fixed in mypy 1.2.

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-play reproduction and compare its two reported errors with the descriptor behavior documented around dataclasses._get_field. Trace the dataclass type-checking path for descriptor fields, including InitVar, and add focused coverage for both cases. Done means mypy reports no errors for the reproduction on the affected Python versions.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.