Skip to content

Dataclasses fields should evaluate their annotations #137891

@Zaharid

Description

@Zaharid

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

7b7b90d#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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions