python / python/cpython

`__future__` annotations breaks `TypedDict` `__required/optional_keys__`

オープン
#97,727 コメント 7 件 リアクション 1 件 担当者 0 名 GitHub で見る

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

stdlib topic-typing type-bug
主要言語
Python
スター
77.2k
フォーク
36k
平均マージ
1日 9時間
マージ済み PR(30日)
558

説明

Bug report

from __future__ import annotations appears to break TypedDict required/optional keys ending up in __required_keys__ and __optional_keys__. mypy works as expected though.

Using the example from https://peps.python.org/pep-0655/#usage-in-python-3-11 as the base

$ cat t.py
from __future__ import annotations

from typing_extensions import NotRequired, TypedDict

class Dog(TypedDict):
    name: str
    owner: NotRequired[str]

print("required", Dog.__required_keys__)
print("optional", Dog.__optional_keys__)
$ python3 t.py
required frozenset({'name', 'owner'})
optional frozenset()

With the __future__ import removed, works as expected:

$ cat t.py
from typing_extensions import NotRequired, TypedDict

class Dog(TypedDict):
    name: str
    owner: NotRequired[str]

print("required", Dog.__required_keys__)
print("optional", Dog.__optional_keys__)
$ python3 t.py
required frozenset({'name'})
optional frozenset({'owner'})

Note: breaks across different variations of total and Required/NotRequired and typing_extensions vs typing imports, above is just one example.

https://peps.python.org/pep-0655/#how-to-teach-this contains an example with the __future__ annotations import in place with no mention that it would not cause __required_keys__ and __optional_keys__ becoming populated as expected, so I'm assuming this is a bug.

Your environment

  • CPython versions tested on:

    • 3.9.7 + NotRequired and TypedDict imports from typing_extensions
    • 3.10.7 + above mentioned imports from typing_extensions
    • current 3.11.0rc2+ + above mentioned imports from typing_extensions
    • current 3.11.0rc2+ above mentioned imports from typing
  • Operating system and architecture: Linux x86_64

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

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

はじめの一歩

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

調査の方向性

まず、一覧にある Python バージョン全体で、from __future__ import annotations の有無を変え、typingtyping_extensions の両方を使って t.py の再現コードを実行します。TypedDictRequiredNotRequired のエントリポイントを追跡し、遅延アノテーションがキーの分類にどのような影響を与えるかを特定します。報告された各バリエーションについて、__required_keys____optional_keys__ が宣言されたアノテーションと一致すれば完了です。

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

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
42/100

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

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