Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: refinement of ReadOnly TypedDict fields in subclasses #18704

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ldeld
Copy link

@ldeld ldeld commented Feb 18, 2025

Fixes #7435

Adds the possibility to refine read-only keys in TypedDicts through inheritance.

The refinement is limited to read-only keys because refining mutable keys leads to unsafe edge cases (see #7435 (comment))

The rules are straight-forward:

  • The original key type and refined type must both be read only
  • The refined type must be a subtype of the original

@hauntsaninja, I saw you were open to receiving a PR for this. This is the first time I look at mypy's source code, so I apologize if the code is not up to standard! (I was particularly unsure if it is OK to modify failure messages.)

Copy link
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

django-stubs (https://github.com/typeddjango/django-stubs): 2.07x faster (51.1s -> 24.6s in a single noisy sample)

@@ -40,6 +39,7 @@
require_bool_literal_argument,
)
from mypy.state import state
from mypy.subtypes import is_subtype
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, it is not safe to call is_subtype() during semantic analysis (except in semanal_typeargs.py which is the last pass, but this is not helpful for you). Some types may not be fully analyzed and this will cause all kinds of weird behaviors.

This kind of checks can be only done during type-checking phase.

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 does not support type refinement in subclasses
2 participants