python / python/cpython

Dataclasses fields should evaluate their annotations

オープン
#137,891 コメント 11 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

pending stdlib topic-dataclasses topic-typing type-feature
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、参照されている CPython のコミットと、annotationlib の ForwardRef モードを読み取る dataclasses のフィールド構築を確認します。その動作を annotations 内の評価済みの値と比較し、続いて互換性のある field.type のセマンティクスを判断し、文書化されている後方互換性に関する懸念に照らして提案された変更を検証します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。