Skip to content

Add: refinement of ReadOnly TypedDict fields in subclasses#18704

Closed
ldeld wants to merge 1 commit intopython:masterfrom
ldeld:typed-dict-readonly-refinement
Closed

Add: refinement of ReadOnly TypedDict fields in subclasses#18704
ldeld wants to merge 1 commit intopython:masterfrom
ldeld:typed-dict-readonly-refinement

Conversation

@ldeld
Copy link
Copy Markdown

@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.)

@github-actions
Copy link
Copy Markdown
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)

Comment thread mypy/semanal_typeddict.py
require_bool_literal_argument,
)
from mypy.state import state
from mypy.subtypes import is_subtype
Copy link
Copy Markdown
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.

@ldeld ldeld closed this Sep 26, 2025
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