python / python/cpython

Dataclasses fields should evaluate their annotations

Offen
#137,891 11 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

pending stdlib topic-dataclasses topic-typing type-feature
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
35.9k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, den referenzierten CPython-Commit und die Konstruktion von dataclasses-Feldern zu überprüfen, die den ForwardRef-Modus von annotationlib liest. Vergleiche dieses Verhalten mit den ausgewerteten Werten in annotations, bestimme anschließend die kompatible Semantik von field.type und validiere die vorgeschlagene Änderung anhand der dokumentierten Bedenken zur Abwärtskompatibilität.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
backend
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.