TypedDict accepts an Enum member as a key and reveals the value type, but KeyErrors at runtime
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
mypy lets you index a TypedDict with an Enum member, and reveal_type gives the correct value type. But it's a KeyError at runtime. Under the hood mypy substitutes the member's .value for the key, a substitution it refuses to make anywhere else.
To Reproduce
from enum import Enum
from typing import Literal, TypedDict
class Foo(Enum):
One = "One"
class TD(TypedDict):
One: int
td: TD = {"One": 1}
d: dict[str, int] = {"One": 1}
reveal_type(td[Foo.One]) # Revealed type is "int" -- accepted
x: Literal["One"] = Foo.One # error: incompatible types -- member is not the literal
d[Foo.One] # error: invalid index type -- not a valid str key
Only the TypedDict line gets through. The other two are rejected, and correctly so: Foo.One is Literal[Foo.One], not Literal["One"], and it isn't a str. So mypy already knows the member isn't its value, everywhere except TypedDict subscription.
At runtime a plain Enum member doesn't compare equal to its value, so the "type-safe" access is the thing that breaks:
>>> td[Foo.One]
KeyError: <Foo.One: 'One'>
Expected Behavior
td[Foo.One] should be an error, the same way d[Foo.One] on a dict[str, int] is. pyright rejects it: "Could not access item in TypedDict."
Actual Behavior
Accepted. reveal_type is int. KeyError when you run it.
One wrinkle worth noting: the only case where the runtime agrees with mypy is a str-mixin enum (StrEnum, or class Foo(str, Enum)), because there the member genuinely is the string. So the acceptance happens to be sound for str enums and is a false negative for every other Enum.
Your Environment
- mypy 2.2.0 (compiled). Reproduces with and without
--strict. - Python 3.12.8
- No flags beyond the above; no plugins.
- For comparison: pyright 1.1.411 flags it.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず mypy で TypedDict と Enum の再現コードを実行し、次に Foo.One を受け入れる原因となっている TypedDict のサブスクリプションの型チェック経路を追跡します。完了条件は、通常の Enum メンバーが dict[str, int] のキーと同様に拒否され、str-mixin の Enum は引き続き受け入れられることです。両方のケースについて regression test を追加または更新してください。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers, devtools
- issue の種類
- バグ
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 静か
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 62/100