Skip to content

Use string values when checking enum TypedDict keys - #21732

Open
snoopuppy582 wants to merge 2 commits into
python:masterfrom
snoopuppy582:agent/fix-typeddict-enum-key
Open

snoopuppy582 wants to merge 2 commits into
python:masterfrom
snoopuppy582:agent/fix-typeddict-enum-key

Conversation

@snoopuppy582

@snoopuppy582 snoopuppy582 commented Jul 14, 2026 •

Copy link
Copy Markdown

Fixes #21722.

TypedDict indexing treats an Enum literal's stored member name as a string key. This accepts plain Enum members that raise KeyError at runtime. For string enums, it can also check the wrong field: name = "value" indexes "value", not "name".

Require a string subtype, then resolve string-enum values through the existing Enum attribute plugin before checking the key. Nested enum values are resolved the same way. Using the Enum descriptor avoids following an overridden .value property; custom constructors with unknown string values and recursive stub declarations are rejected as nonliteral keys.

The regressions cover ordinary Enum reads and writes, both string-enum forms, mismatched names and values, literal unions, nested values, overridden properties and unsupported constructors. The four new cases fail on the previous PR head and pass with this change.

Validation on Windows, Python 3.13.12:

  • TypedDict and Enum data suites: 496 passed.
  • Mypy self-check: 196 source files passed.
  • Changed-file pre-commit hooks and git diff --check: passed.
  • A check against the real typeshed agrees with five runtime lookups and rejects both KeyError controls.

TypedDict indexing treated any string-valued LiteralType as a string literal, including ordinary enum members whose literal value stores the member name. Require the literal fallback to be a subtype of str, while preserving StrEnum and string-mixin enum keys.

Fixes python#21722.
@github-actions

This comment has been minimized.

@snoopuppy582
snoopuppy582 marked this pull request as ready for review September 6, 2026 00:21
@snoopuppy582 snoopuppy582 changed the title Reject non-string enum members as TypedDict keys Use string values when checking enum TypedDict keys Oct 7, 2026
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TypedDict accepts an Enum member as a key and reveals the value type, but KeyErrors at runtime

1 participant