python / python/cpython

Dataclasses fields should evaluate their annotations

Open
#137,891 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

pending stdlib topic-dataclasses topic-typing type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

Proposal:

In Python 3.14 (a5), I was surprised that while

import dataclasses

@dataclasses.dataclass
class X:
    a: X | None

print(X.__annotations__)

works as expected and prints,

{'a': __main__.X | None}

if one tries to look at the type of the field using the dataclasses.fields interface:

print(dataclasses.fields(X)[0].type)

then this instead results in a ForwardRef

ForwardRef('X | None')

Surely, someone trying to inspect the field would want the value version, consistent with the new default functionality of __annotations__ rather than trying to figure out how to evaluate the ForwardRef precisely.

The current behaviour was introduced in

https://github.com/python/cpython/commit/7b7b90d1ce5116f29ad6c8120c0490824baa54e0#diff-44ce2dc1c4922b2f5cf7631d8f86cc569a4c25eb003aaecdc2bc22eb9163d5f5R986

where the dataclasses fields are constructed by reading the ForwardRef mode of annotationlib.

I believe this would be backwards in that the type value had to exists without from __future__ import annotations and would be a string with it.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

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 by reviewing the referenced CPython commit and the dataclasses field construction that reads annotationlib's ForwardRef mode. Compare that behavior with the evaluated values in annotations, then determine the compatible field.type semantics and validate the proposed change against the documented backward-compatibility concerns.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.