GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Implement support for closed TypedDicts (PEP 728) by alicederyn · Pull Request #21382 · python/mypy

Implement support for closed TypedDicts (PEP 728) #21382

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.

Sign up for GitHub

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

Merged
ilevkivskyi merged 43 commits into python:master from alicederyn:closed.keyword
Jun 2, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

Implement support for closed TypedDicts (PEP 728) #21382

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
fa59235
Support nested special forms in functional syntax
alicederyn Apr 29, 2026
c06fef7
Subtypes fix: required keys must remain required
alicederyn Apr 22, 2026
4a82d3c
Meet fix: mutable keys must remain mutable
alicederyn Apr 22, 2026
ca099f4
Improve TypedDict meet
alicederyn Apr 22, 2026
f79ba70
Join fix: readonly keys must remain readonly
alicederyn Apr 22, 2026
2ed7992
Improve TypedDict join
alicederyn Apr 22, 2026
ab1a151
Expand TypedDict subclassing tests
alicederyn May 1, 2026
e626c19
Support type refinement in TypedDict subclasses
alicederyn May 1, 2026
d8c619d
Fix TypeAnalyser to retain readonly keys
alicederyn Apr 30, 2026
e7372e4
Narrow on explicitly uninhabited keys
alicederyn Apr 30, 2026
c7115c1
Support parsing TypedDict closed keyword
alicederyn Apr 23, 2026
bce4b17
Implement closed support in TypedDict subtyping
alicederyn Apr 27, 2026
90cb21f
Implement closed support in subclassing
alicederyn Apr 24, 2026
4106525
Implement closed support in join logic
alicederyn Apr 28, 2026
6cc0d63
Implement closed support in meet logic
alicederyn Apr 29, 2026
5bfcc43
Implement closed support in narrowing
alicederyn Apr 30, 2026
d7449df
Implement TypeVar support in narrowing
alicederyn Apr 30, 2026
2621704
Implement closed support in astdiff
alicederyn Apr 30, 2026
34a13de
Implement closed support in stubgen
alicederyn Apr 30, 2026
87ede99
Implement closed support in serialization
alicederyn Apr 30, 2026
bbdd827
Implement closed support in TypeAnalyser
alicederyn Apr 30, 2026
c1ff8b3
Implement closed support in unpacking
alicederyn Apr 30, 2026
ca5a13f
Implement closed support in expandtype
alicederyn May 1, 2026
4d3a7b0
Implement closed support in get method
alicederyn May 1, 2026
877e000
Merge branch 'master' into closed.keyword
alicederyn May 19, 2026
6f3291b
Fix bug with join and Any
alicederyn May 19, 2026
776eb10
Fix bug with meet and Any
alicederyn May 19, 2026
05d3a4b
Refactor common logic into zipall
alicederyn May 19, 2026
022a501
Fix assumption that missing items are ReadOnly
alicederyn May 19, 2026
bd05e88
Allow adding Never items to closed subtypes
alicederyn May 19, 2026
d102505
Reword not-required compatibility error messages
alicederyn May 19, 2026
9279a01
Test case from no error to error
alicederyn May 19, 2026
2d1333c
Delay subtype validation to TypeChecker
alicederyn May 18, 2026
4ee7856
Add closed keyword to TypedDict docs
alicederyn May 20, 2026
8bcc243
Store validation information in TypeInfo
alicederyn May 26, 2026
77e8a59
Link TypedDict branch narrowing to test cases
alicederyn May 26, 2026
4261abb
Remove references to 'MRO'
alicederyn May 26, 2026
8d92a10
Extend subclass tests with subtype checks
alicederyn May 26, 2026
37481a2
Merge branch 'master' into closed.keyword
alicederyn May 26, 2026
42ec16f
Manually wrap strings/comments
alicederyn Jun 1, 2026
5cbb687
Remove unnecessary extra newline
alicederyn Jun 1, 2026
31b5045
Document new TypedDict inheritance rules
alicederyn Jun 1, 2026
fbd2818
Merge branch 'master' into closed.keyword
alicederyn Jun 2, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
Support type refinement in TypedDict subclasses
Allow readonly keys to be refined in subclasses, in line with PEP 705.
For cases where refinement is not permitted by spec, provide a more
detailed error message.

As placeholders may now affect validation without ending up in the final
TypedDictType, an `analysis_incomplete` field has been added, triggering
reanalysis in subsequent rounds.

This closes #7435
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@alicederyn
alicederyn committed May 3, 2026
commit e626c19bacd9d8323d21522fb5ae2d945dc9e8c4

There are no files selected for viewing

2 changes: 1 addition & 1 deletion 2 mypy/semanal.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2108,7 +2108,7 @@ def analyze_typeddict_classdef(self, defn: ClassDef) -> bool:
if (
defn.info
and defn.info.typeddict_type
and not has_placeholder(defn.info.typeddict_type)
and not defn.info.typeddict_type.analysis_incomplete
Comment thread Outdated

@ilevkivskyi ilevkivskyi May 22, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Using a flag instead of an extra has_placeholder() check(s) is a good idea, but same thing I mentioned before applies here, I would rather store this information on the TypeInfo. For example, something like info.typeddict_data.ready.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

alicederyn reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
):
# This is a valid TypedDict, and it is fully analyzed.
return True
Expand Down
260 changes: 203 additions & 57 deletions 260 mypy/semanal_typeddict.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@

from __future__ import annotations

from collections.abc import Collection
from typing import Final
from typing import Final, NamedTuple

from mypy import errorcodes as codes, message_registry
from mypy.errorcodes import ErrorCode
from mypy.expandtype import expand_type
from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type
from mypy.message_registry import TYPEDDICT_OVERRIDE_MERGE
Comment thread

@ilevkivskyi ilevkivskyi May 29, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Is this constant still used anywhere? If not, you can just delete it. (Btw you can also put some of your error messages in message_registry if you want).

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@alicederyn alicederyn Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

It's still used in TypeAnalyser.visit_typeddict_type for experimental inline TypedDicts

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
from mypy.messages import MessageBuilder
from mypy.nodes import (
ARG_NAMED,
Expand Down Expand Up @@ -41,6 +39,7 @@
require_bool_literal_argument,
)
from mypy.state import state
from mypy.subtypes import is_equivalent, is_subtype
Comment thread Outdated

@ilevkivskyi ilevkivskyi May 16, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Using is_subtype() (and in general any type-checking operations) is not safe during semantic analysis. I can give more details if you want, but it is a very hard rule. The earliest stage where type checking is acceptable is semanal_typeargs (one of semantic analysis post-processing passes), but even there it should be done only if absolutely necessary.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

alicederyn reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

@alicederyn alicederyn May 17, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

All I'm using this for is to flag an error if the selected field type is incompatible with any base definition, so I can easily move it to whichever stage of the analysis you recommend.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@ilevkivskyi ilevkivskyi May 17, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I think it should probably be somewhere in checker.py in visit_class_def().

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

alicederyn reacted with eyes emoji
All reactions
  • 👀 1 reaction

@alicederyn alicederyn May 20, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I couldn't see a way to nicely get the typeddict base classes in checker.py, and I'm not super confident in my workaround. Please let me know what you think, especially if there's a better solution I missed.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@ilevkivskyi ilevkivskyi May 21, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Yeah, this is not the best way to do it. Couple problems I see are:

  • Adding a new attribute to a type has a relatively large performance impact
  • At a point where you record the constraint, the type may not be ready yet (has placeholders)

I think what you should do instead is:

  • Record the relevant information as TypeInfo.typeddict_bases attribute that would have type list[TypedDictType] | None. IIUC you don't need to serialize this attribute (since TypedDict subtyping is structural).
  • Update the self.api.process_placeholder() call to also cover the TypedDict bases.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@alicederyn alicederyn May 22, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I'm not quite sure I understand, I'm afraid.

  1. Isn't that still adding a new attribute to a type?
  2. Would the name typeddict_bases risk people accidentally using it in future without realising it's not serialized?
  3. How would we know what the field source was in order to make a readable error message (e.g. Incompatible definitions of field "key" in base classes "B" and "A" vs Definition of field "key" incompatible with base class "A")? That information is currently part of the "constraint" type, and it's not recoverable from the current info + the bases.

I can definitely reduce the amount of information stored quite a lot -- or I can clear out the whole field once the checker has used it?

The process_placeholder call is already updated to be invoked if a constraint has recorded a placeholder, and the analysis_incomplete flag is making sure the object is regenerated in a subsequent round.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@ilevkivskyi ilevkivskyi May 22, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

OK, I can give you some more context.

Isn't that still adding a new attribute to a type?

No. Despite the name, TypeInfo is a symbol (i.e. SymbolNode), while TypedDictType is a ProperType. 10-100x more types than symbols are created when type-checking typical code (because each expression is assigned a type, plus types are semantically immutable, so we copy them a lot). This is why types should be kept "lightweight", as compared to symbols (when possible). Another important point: having an extra attribute will have impact even if most objects will not use it (since mypy classes are compiled to structs).

Would the name typeddict_bases risk people accidentally using it in future without realising it's not serialized?

I am not worried about this. Since parallel checking uses incremental cache, chances this will not be caught in tests is ~0%. But I am also not attached to a specific name (see also below).

That information is currently part of the "constraint" type, and it's not recoverable from the current info + the bases.

This is a good point. You should store the minimum needed to perform the checks. It seems to me having typeddict_bases + items that were overridden should be enough, but maybe I am missing some edge cases.

I can definitely reduce the amount of information stored quite a lot

This is exactly what I want. In particular, eagerly creating error message strings looks like a bad idea, since they will not be used in 99.9% of code (most code people type-check doesn't have type errors).

The process_placeholder call is already updated to be invoked if a constraint has recorded a placeholder, and the analysis_incomplete flag is making sure the object is regenerated in a subsequent round.

OK, I missed this. I looked at this part, and I think I see some problems. I will leave few inline comment there soon.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@alicederyn alicederyn May 23, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Thank you, just what I needed spelled out! I'll get on this next week.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@alicederyn alicederyn May 26, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

If we only store a list of TypedDictType, we'll need to duplicate the logic for fetching base keys from TypedDictAnalyzer. I opted to store the computed dict as well, LMK if you'd rather I refactored the code that computes the dicts to be shared with TypeChecker

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type
from mypy.types import (
TPDICT_NAMES,
Expand All @@ -59,6 +58,14 @@
)


class FieldSource(NamedTuple):
field_type: Type
is_readonly: bool
is_required: bool
base_name: str | None = None
child_field_ctx: AssignmentStmt | None = None


class TypedDictAnalyzer:
def __init__(
self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder
Expand Down Expand Up @@ -101,20 +108,20 @@ def analyze_typeddict_classdef(self, defn: ClassDef) -> tuple[bool, TypeInfo | N
if isinstance(defn.analyzed, TypedDictExpr):
existing_info = defn.analyzed.info

field_types: dict[str, Type] | None
if (
len(defn.base_type_exprs) == 1
and isinstance(defn.base_type_exprs[0], RefExpr)
and defn.base_type_exprs[0].fullname in TPDICT_NAMES
):
# Building a new TypedDict
field_types, statements, required_keys, readonly_keys = (
self.analyze_typeddict_classdef_fields(defn)
)
if field_types is None:
field_sources, statements = self.analyze_typeddict_classdef_fields(defn)
if field_sources is None:
return True, None # Defer
if self.api.is_func_scope() and "@" not in defn.name:
defn.name += "@" + str(defn.line)
field_types = {key: source.field_type for (key, source) in field_sources.items()}
required_keys = {key for (key, source) in field_sources.items() if source.is_required}
readonly_keys = {key for (key, source) in field_sources.items() if source.is_readonly}
info = self.build_typeddict_typeinfo(
defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info
)
Expand Down Expand Up @@ -154,45 +161,41 @@ def analyze_typeddict_classdef(self, defn: ClassDef) -> tuple[bool, TypeInfo | N
else:
self.fail("All bases of a new TypedDict must be TypedDict types", defn)

field_types = {}
required_keys = set()
readonly_keys = set()
# Iterate over bases in reverse order so that leftmost base class' keys take precedence
for base in reversed(typeddict_bases):
self.add_keys_and_types_from_base(
base, field_types, required_keys, readonly_keys, defn
)
new_field_types, new_statements, new_required_keys, new_readonly_keys = (
self.analyze_typeddict_classdef_fields(defn, oldfields=field_types)
)
if new_field_types is None:
bases_info: list[tuple[TypeInfo, dict[str, Type]]] = []
for base in typeddict_bases:
base_info = self.fetch_keys_and_types_from_base(base, defn)
if base_info is not None:
bases_info.append(base_info)
new_field_sources, new_statements = self.analyze_typeddict_classdef_fields(defn)
if new_field_sources is None:
return True, None # Defer
field_types.update(new_field_types)
required_keys.update(new_required_keys)
readonly_keys.update(new_readonly_keys)
field_types, required_keys, readonly_keys, any_placeholders = (
self.resolve_field_inheritance(bases_info, new_field_sources, defn)
)
info = self.build_typeddict_typeinfo(
defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info
defn.name,
field_types,
required_keys,
readonly_keys,
defn.line,
existing_info,
analysis_incomplete=any_placeholders,
)
defn.analyzed = TypedDictExpr(info)
defn.analyzed.line = defn.line
defn.analyzed.column = defn.column
defn.defs.body = new_statements
return True, info

def add_keys_and_types_from_base(
self,
base: Expression,
field_types: dict[str, Type],
required_keys: set[str],
readonly_keys: set[str],
ctx: Context,
) -> None:
def fetch_keys_and_types_from_base(
self, base: Expression, ctx: Context
) -> tuple[TypeInfo, dict[str, Type]] | None:
info = self._parse_typeddict_base(base, ctx)
base_args: list[Type] = []
if isinstance(base, IndexExpr):
args = self.analyze_base_args(base, ctx)
if args is None:
return
return None
base_args = args

assert info.typeddict_type is not None
Expand All @@ -211,13 +214,159 @@ def add_keys_and_types_from_base(

with state.strict_optional_set(self.options.strict_optional):
valid_items = self.map_items_to_base(valid_items, tvars, base_args)
for key in base_items:
if key in field_types:
self.fail(TYPEDDICT_OVERRIDE_MERGE.format(key), ctx)

field_types.update(valid_items)
required_keys.update(base_typed_dict.required_keys)
readonly_keys.update(base_typed_dict.readonly_keys)
return info, valid_items

def field_sources_in_reverse_mro(
Comment thread Outdated

@ilevkivskyi ilevkivskyi May 21, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

This name is misleading, since we are only checking compatibility with immediate bases. And to be clear this is the right thing to do, since TypeDicts are structural and are constructed eagerly (i.e. they don't have an MRO).

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

alicederyn reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
self,
bases: list[tuple[TypeInfo, dict[str, Type]]],
child_field_sources: dict[str, FieldSource],
) -> dict[str, list[FieldSource]]:
"""Find all keys in bases and child, mapping them to a list of sources.

Iterate bases in reverse order to preserve key ordering for display.
"""
result: dict[str, list[FieldSource]] = {}
for base_info, base_fields in reversed(bases):
assert base_info.typeddict_type is not None
for field_name, field_type in base_fields.items():
source = FieldSource(
base_name=base_info.name,
field_type=field_type,
is_readonly=field_name in base_info.typeddict_type.readonly_keys,
is_required=field_name in base_info.typeddict_type.required_keys,
)
result.setdefault(field_name, []).append(source)
for field_name, source in child_field_sources.items():
result.setdefault(field_name, []).append(source)
return result

def primary_source(self, sources: list[FieldSource]) -> FieldSource:
"""Select a primary source from a reverse-MRO-ordered list of sources.

The primary source will be the last in the MRO list, skipping readonly
Comment thread Outdated

@ilevkivskyi ilevkivskyi May 22, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Just noticed another place where you mention MRO. Instead say reverse order of immediate bases (or something similar).

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

alicederyn reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
base class sources unless they are the only available option.
"""
if sources[-1].child_field_ctx:
return sources[-1]
mutable_sources = (s for s in reversed(sources) if not s.is_readonly)
return next(mutable_sources, sources[-1])

def verify_field_compatibility(
self,
field_name: str,
source: FieldSource,
field_type: Type,
is_readonly: bool,
is_required: bool,
primary_source_base_name: str | None,
ctx: Context,
) -> None:
"""Verify compatibility of the final child type field with a base class source.

Verifies type compatibility, requiredness, and mutability.
"""
if has_placeholder(field_type) or has_placeholder(source.field_type):
# Cannot verify type compatibility yet, but analysis will be deferred
# and rerun later
is_type_compatible = True
elif source.is_readonly:
is_type_compatible = is_subtype(field_type, source.field_type)
else:
is_type_compatible = is_equivalent(field_type, source.field_type)
if not is_type_compatible:
if primary_source_base_name is None:
self.fail(
f'Definition of field "{field_name}" incompatible with base class "{source.base_name}"',
ctx,
)
else:
self.fail(
f'Incompatible definitions of field "{field_name}" in base classes "{source.base_name}" and "{primary_source_base_name}"',
ctx,
)
if is_readonly:
self.note(
f'This can be resolved by redeclaring the field "{field_name}" with a mutually compatible type',
ctx,
)
elif source.is_required and not is_required:
if primary_source_base_name is None:
self.fail(
f'Field "{field_name}" is required in base class "{source.base_name}"', ctx
)
else:
self.fail(
f'Field "{field_name}" is required in base class "{source.base_name}" but not in base class "{primary_source_base_name}"',
ctx,
)
elif not source.is_required and not source.is_readonly and is_required:
if primary_source_base_name is None:
self.fail(
f'Field "{field_name}" is not required and not readonly in base class "{source.base_name}"',
ctx,
)
else:
self.fail(
f'Field "{field_name}" is required in base class "{primary_source_base_name}" but not in base class "{source.base_name}"',
ctx,
)

def resolve_field_inheritance(
self,
bases: list[tuple[TypeInfo, dict[str, Type]]],
child_field_sources: dict[str, FieldSource],
ctx: Context,
) -> tuple[dict[str, Type], set[str], set[str], bool]:
"""Determine field types, requiredness, and readonlyness.

Additionally returns if any placeholders were seen, as they will prevent full
analysis, but may not result in placeholders in the final type.
"""
field_sources = self.field_sources_in_reverse_mro(bases, child_field_sources)
field_types: dict[str, Type] = {}
required_keys: set[str] = set()
readonly_keys: set[str] = set()
any_placeholders = False

for field_name, sources in field_sources.items():
primary_source = self.primary_source(sources)
# If a read-only field is only defined in base classes, joining the types
# is unlikely to produce a tight enough result. We could check all the
# candidates from the base classes, but it would be O(n^2) complexity
# to find out which is a supertype of all the others. Instead, use the
# first definition in MRO order, and let the user provide the correct
# definition in the subclass if this fails.
Comment thread

@ilevkivskyi ilevkivskyi May 29, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

This behavior is worth documenting (with a short example). It is not obvious to a user which base takes precedence: first or last.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

alicederyn reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
field_types[field_name] = primary_source.field_type

if primary_source.is_readonly:
# If the primary source is readonly, all sources are readonly
is_readonly = True
is_required = any(source.is_required for source in sources)
else:
is_readonly = False
is_required = primary_source.is_required

if is_required:
required_keys.add(field_name)
if is_readonly:
readonly_keys.add(field_name)

for source in sources:
if has_placeholder(source.field_type):
any_placeholders = True
if source is not primary_source:
self.verify_field_compatibility(
field_name,
source,
field_types[field_name],
is_readonly,
is_required,
primary_source.base_name,
primary_source.child_field_ctx or ctx,
)

return field_types, required_keys, readonly_keys, any_placeholders

def _parse_typeddict_base(self, base: Expression, ctx: Context) -> TypeInfo:
if isinstance(base, RefExpr):
Expand Down Expand Up @@ -288,22 +437,19 @@ def map_items_to_base(
return mapped_items

def analyze_typeddict_classdef_fields(
self, defn: ClassDef, oldfields: Collection[str] | None = None
) -> tuple[dict[str, Type] | None, list[Statement], set[str], set[str]]:
self, defn: ClassDef
) -> tuple[dict[str, FieldSource] | None, list[Statement]]:
"""Analyze fields defined in a TypedDict class definition.

This doesn't consider inherited fields (if any). Also consider totality,
if given.

Return tuple with these items:
* Dict of key -> type (or None if found an incomplete reference -> deferral)
* Dict of key -> field source (or None if found an incomplete reference -> deferral)
* List of statements from defn.defs.body that are legally allowed to be a
part of a TypedDict definition
* Set of required keys
"""
fields: dict[str, Type] = {}
readonly_keys = set[str]()
required_keys = set[str]()
fields: dict[str, FieldSource] = {}
statements: list[Statement] = []

total: bool | None = True
Expand Down Expand Up @@ -333,8 +479,6 @@ def analyze_typeddict_classdef_fields(
self.fail(TPDICT_CLASS_ERROR, stmt)
else:
name = stmt.lvalues[0].name
if name in (oldfields or []):
self.fail(f'Overwriting TypedDict field "{name}" while extending', stmt)
if name in fields:
self.fail(f'Duplicate TypedDict key "{name}"', stmt)
continue
Expand All @@ -353,18 +497,18 @@ def analyze_typeddict_classdef_fields(
prohibit_special_class_field_types="TypedDict",
)
if analyzed is None:
return None, [], set(), set() # Need to defer
return None, [] # Need to defer
field_type = analyzed
if not has_placeholder(analyzed):
stmt.type = self.extract_meta_info(analyzed, stmt)[0]

field_type, required, readonly = self.extract_meta_info(field_type)
fields[name] = field_type

if (total or required is True) and required is not False:
required_keys.add(name)
if readonly:
readonly_keys.add(name)
fields[name] = FieldSource(
field_type=field_type,
is_required=(total or required is True) and required is not False,
is_readonly=readonly,
child_field_ctx=stmt,
)

# ...despite possible minor failures that allow further analysis.
if stmt.type is None or hasattr(stmt, "new_syntax") and not stmt.new_syntax:
Expand All @@ -373,7 +517,7 @@ def analyze_typeddict_classdef_fields(
# x: int assigns rvalue to TempNode(AnyType())
self.fail("Right hand side values are not supported in TypedDict", stmt)

return fields, statements, required_keys, readonly_keys
return fields, statements

def extract_meta_info(
self, typ: Type, context: Context | None = None
Expand Down Expand Up @@ -597,6 +741,7 @@ def build_typeddict_typeinfo(
readonly_keys: set[str],
line: int,
existing_info: TypeInfo | None,
analysis_incomplete: bool = False,
) -> TypeInfo:
# Prefer typing then typing_extensions if available.
fallback = (
Expand All @@ -607,7 +752,8 @@ def build_typeddict_typeinfo(
assert fallback is not None
info = existing_info or self.api.basic_new_typeinfo(name, fallback, line)
typeddict_type = TypedDictType(item_types, required_keys, readonly_keys, fallback)
if has_placeholder(typeddict_type):
if has_placeholder(typeddict_type) or analysis_incomplete:
typeddict_type.analysis_incomplete = True
self.api.process_placeholder(
None, "TypedDict item", info, force_progress=typeddict_type != info.typeddict_type
Comment thread Outdated

@ilevkivskyi ilevkivskyi May 22, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I think force_progress should be updated as well, to match the logic few lines above.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

alicederyn reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
)
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

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.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.