Reject non-string enum members as TypedDict keys#21732
Draft
snoopuppy582 wants to merge 1 commit into
Draft
Conversation
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.
Contributor
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
TypedDict indexing currently accepts any
LiteralTypewhose stored value is a string. Enum literals also store their member name as a string, so a plain Enum member such asPlainEnum.foois mistaken for the key"foo"even though the member is not astrand the lookup raisesKeyErrorat runtime.Require the literal fallback to be a subtype of
strbefore using its value as a TypedDict key. This rejects ordinary Enum members while preserving bothStrEnumandclass E(str, Enum)members, which are valid string keys at runtime.The regression test covers reads and writes with a plain Enum and successful reads with both string-backed Enum forms.
Fixes #21722.
Validation
python -m pytest -n0 mypy/test/testcheck.py::TypeCheckSuite::check-typeddict.test(362 passed)python runtests.py self(341 source files checked)python runtests.py lint(all hooks passed)AI assistance
I used OpenAI Codex to help reproduce the issue, trace the TypedDict index-checking path, draft the focused code and regression-test changes, and run the local validation above. The submitted change and any follow-up remain my responsibility.