Change the rules for structural subtyping of TypedDicts:… #12142
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.
… a TypedDict with a more-specific type is now considered a subtype of a TypedDict with a less-specific type.
Examples:
{'a': str}is now a subtype of{'a': NotRequired[str]}{'a': str}is now a subtype of{'a': Optional[str]}This PR came up in the context of #12095 - in that PR I wrote a narrowing pass that would narrow the required properties of typed dicts with code that checked properties like
"key" in td. Except that was causing errors because the narrowed type was considered incompatible with the original type.This does somewhat alter the ergonomics and safety guarantees of the type system: because you could then do things like mutate the more generic type and make changes that were incompatible with the specific type. However in most structural-subtyping systems (including typescript), you're allowed to convert from a more-specific type to the less-specific type, with the understanding that this could allow type-incorrect mutations to occur.
Test Plan
Automated/unit tests cover the primary functionality of this PR. I await the mypy_primer results: I do not expect any errors as this PR is strictly looser than previously, but it's possibly that type-ignore comments are no longer required in some places.
@davidfstr @JukkaL tagging you because of your prior relationship with TypedDict typing and this code.