Skip to content

Update unpack TypedDict kwargs forwarding spec + add conformance tests - #2338

Open
yangdanny97 wants to merge 16 commits into
python:mainfrom
yangdanny97:typeddict-kwargs-passing
Open

yangdanny97 wants to merge 16 commits into
python:mainfrom
yangdanny97:typeddict-kwargs-passing

Conversation

@yangdanny97

Copy link
Copy Markdown
Contributor

Previously, this section of the spec was not exercised at all in the conformance tests, and also was not implemented by any type checker.

This PR updates the spec to account for closed & extra_items TypedDicts, and adds conformance tests.

There are 3 asserted errors:

  • open TypedDict kwargs being unpacked into function w/o kwargs (no type checker implements this)
  • extra_items TypedDict kwargs being unpacked into function w/o kwargs (only ty implements this)
  • extra_items TypedDict kwargs being unpacked into function w/ incompatibly-typed kwargs (ty, pyright, and zuban implement this)

This would supersede #1960, which proposed that we delete the section of the spec entirely.
@rchen152's comment in https://discuss.python.org/t/typing-spec-inconsistency-for-unpacking-typed-dict-kwargs/79640 favors deletion.

@yangdanny97 yangdanny97 changed the title Add tests for unpack TypedDict kwargs forwarding Update unpack TypedDict kwargs forwarding spec + add conformance tests Aug 11, 2026
@carljm

carljm commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

This issue is nuanced, because many unpacking behaviors in Python are unsafe. If you unpack a list[int] into a function that takes (int, int) (but not *args: int), every type checker allows that, even though the list could obviously contain fewer or more than two elements. The collective decision seems to be that since length is not part of what the list type encodes, we trust the user rather than erroring.

In ty we made the decision not to error on the first case here, because we saw large mypy-primer fallout if we enforced this rule, and we felt it was analogous to the case of list[int] -- an open TypedDict may contain extra elements (just like a list may contain any number of elements), but the type doesn't explicitly say that it does, so we can be forgiving here.

We decided to be stricter with extra_items, in part because there is no widespread usage yet, so usage will adapt to what type checkers permit, and in part because in this case the user has explicitly declared their intent for the TypedDict to contain extra items, so it feels reasonable to account for that more strictly. This does mean that implicitly open typed dicts are not equivalent to extra_items=ReadOnly[object], which maybe in principle they would be -- but I think this is currently true in all type checkers.

I think ty's compromise is reasonable, but I'm not totally convinced it's the best option, open to other resolutions here. But enforcing this rule on all implicitly open TypedDicts will have a significant impact on existing real-world code.

@yangdanny97

Copy link
Copy Markdown
Contributor Author

For Pyrefly my current thought is that this would be off-by-default and enabled in strict mode.

@carljm

carljm commented Aug 11, 2026

Copy link
Copy Markdown
Member

That seems reasonable. I'm not sure if behavior that we wouldn't turn on by default in our own type checkers should be encoded as a conformance suite requirement, though?

It seems to me that a strict mode which requires safety in unpacking an open TypedDict should probably also require safety in unpacking a list/Sequence?

@yangdanny97

yangdanny97 commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor Author

So do you think that we should just merge #1960 and delete this section from the typing spec entirely?

Or weaken the first assertion to "may" and "E?"

@carljm

carljm commented Aug 11, 2026

Copy link
Copy Markdown
Member

I would probably land this with the first assertion weakened (and discussion of that in the spec also), but that's not a strong preference, it just matches what we decided to do in ty, so naturally it already makes sense to me :) Very open to other opinions here.

@yangdanny97

Copy link
Copy Markdown
Contributor Author

Does it make sense to differentiate between implicitly open and explicitly open (closed=False), by making errors mandatory for the latter?

@carljm

carljm commented Aug 12, 2026

Copy link
Copy Markdown
Member

Does it make sense to differentiate between implicitly open and explicitly open (closed=False), by making errors mandatory for the latter?

It might. Currently in ty we only apply the extra strictness with extra_items=, not with closed=False. I think the appeal of this is that keeps closed itself boolean rather than tri-valued (that is, closed=False is the default and providing it explicitly makes no difference), but closed=False alone is not the same thing as explicitly providing an extra_items type -- the latter more explicitly says "I expect there to be extra items in this dict of a particular type". But all of this is a judgment call, there's no clear right or wrong answer. Or rather, the "right" answer in the abstract is probably the universal strictness you initially proposed, it's just a question of whether that's workable in the ecosystem.

@JelleZijlstra

Copy link
Copy Markdown
Member

The current TypedDict spec says that closed=False means the TypedDict is open, i.e. consistent with the default. I think we should stick with the TypedDict spec chapter's clear division of TypedDicts into states, and allow unsound behavior only if the TypedDict is open (as defined by the spec; the spec change in this PR should link to the glossary definition for the term).

In the abstract I'd prefer to treat open TypedDicts similar to ones with extra_items=ReadOnly[object], but I agree that's probably a bridge too far right now.

@carljm carljm left a comment

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.

Thank you!

Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved
Comment thread docs/spec/callables.rst Resolved

@carljm carljm left a comment

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.

I think there are a couple details here in the spec (one backwards statement, one broken link) that should be addressed -- everything else here is up to you whether you want to include it in this PR. Otherwise this looks ready to me.

I'm glad we are clearing this up now, before wider adoption of closed/extra_items TypedDicts.

Comment thread docs/spec/callables.rst Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved
Comment thread docs/spec/callables.rst Resolved

@carljm carljm left a comment

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.

I'm happy with this.

I guess since it touches the spec and the conformance suite, we need a Discuss thread, the one-week wait, and an issue for Typing Council sign-off?

@yangdanny97

Copy link
Copy Markdown
Contributor Author

@davidhalter

davidhalter commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Sorry for taking such a long time here. I have tried to play with this quite a bit in Zuban to get a feel for it and I'm favorable to merging this PR. There have been two potential cases that I would like to add to the spec (please let me know if you disagree):

from typing import TypedDict
from typing_extensions import Unpack

class Person(TypedDict):
    name: str
    age: int

class Base:
    def foo(self, **kwargs: Unpack[Person]) -> None: ...
class SubGood(Base):
    def foo(self, *, name: str, age: int, extra: bool = False) -> None: ...   # Should probably error here?!

This is currently not an error in Zuban/Mypy (test is called testUnpackKwargsOverrides in Mypy), but likely should be. I want to avoid type checkers using different logic for normal callable subtyping and inheritance checking.

Another case of callable subtyping that I looked at was this one that might be worth to add:

from typing import Never, Unpack, TypedDict

class TDBase(TypedDict):
    x: int

class TD(TDBase, total=False):
    y: int

def a1(**kwargs: Unpack[TDBase]) -> None: .
def a2(**kwargs: Unpack[TD]) -> None: ...

if bool():
    a1 = a2  # (1) This should error
else:
    a2 = a1  # (2)

Before my changes to think of non-closed TypedDicts in Unpacks as essentially having extra_items=object, (2) had an error, now it's the other way around (1) errors. This is definitely better, it was buggy before. It feels like this isn't really part of the tests yet and I think it's central to this view of TypedDicts.

(I'm aware that this might not be an issue in other type checker, because it just widens the type. But you can also create this case with Protocols like a1: <some protocol that mimics a1> = a2)


I'm also open to the make some of the # E? to # E, but I don't have a strong opinion here, especially after Carl's discovery that the impact is not as bad.

@yangdanny97
yangdanny97 force-pushed the typeddict-kwargs-passing branch from 20a9e41 to 770b585 Compare August 28, 2026 03:22
@yangdanny97

yangdanny97 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Okay, based on the dsicussion in the forum thread, I've updated the docs and tests to require the error.

@yangdanny97

Copy link
Copy Markdown
Contributor Author

I haven't had time to look into @davidhalter's examples yet, will do so when i hvae time

@carljm carljm left a comment

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.

Looks good! A few things I noticed inline.

Comment thread docs/spec/callables.rst Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved

@carljm carljm left a comment

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.

Looks great!

meta-codesync Bot pushed a commit to pyrefly-org/pyrefly that referenced this pull request Sep 11, 2026
Summary:
python/typing#2338 added a bunch of conformance tests and rules in the spec.

This PR adds those test cases to Pyrefly's suite and makes Pyrefly pass them.

Only the open typed dict rules get the special open-unpacking error code to be off-by-default, the rest get normal errors.

Pull Request resolved: #4714

Test Plan: added tests

Reviewed By: kinto0

Differential Revision: D117964929

Pulled By: rchen152

fbshipit-source-id: 031d4578f0a2688f7675413f13f20a6dd70c35c0
@srittau srittau added topic: typing spec For improving the typing spec topic: conformance tests Issues with the conformance test suite labels Nov 18, 2026
@yangdanny97

Copy link
Copy Markdown
Contributor Author

bump

@carljm

carljm commented Nov 24, 2026

Copy link
Copy Markdown
Member

Oops, sorry we let this one drop. @davidhalter and @jorenham it looks like we need your approvals on python/typing-council#64 in order to move forward here. @yangdanny97 once we've got those approvals in principle, do you mind rebasing the PR? Then I'd give it a final once-over and merge it.

@davidhalter

davidhalter commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

I intentionally did not check the box, because @yangdanny97 wrote that he wants to look at my examples:

I haven't had time to look into @davidhalter's examples yet, will do so when i have time

I don't think this has happened yet, I don't find any comments or commits about it.

@yangdanny97
yangdanny97 force-pushed the typeddict-kwargs-passing branch from 1c5c7f4 to b45c105 Compare November 24, 2026 23:57
@python-cla-bot

python-cla-bot Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@yangdanny97

Copy link
Copy Markdown
Contributor Author

Oops my bad, I thought I had addressed it already. Will take a look tn

@yangdanny97

Copy link
Copy Markdown
Contributor Author

@davidhalter I added the proposed spec changes and test cases

I think the behaviors are already implied by the existing text; the first rule by the requirement that the destination TypedDict be assignable to the source, and the second rule by the definition of override using assignability, but the clarifications make it more explicit so that's good I think.

@davidhalter

Copy link
Copy Markdown
Collaborator

Thanks @yangdanny97

Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst
Comment on lines +390 to +391
Unpacking a TypedDict as keyword arguments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
Unpacking a TypedDict as keyword arguments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Unpacking a TypedDict as keyword argument types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst
@@ -235,10 +235,10 @@
f(name="No Country for Old Men", year=2007) # Not OK. Unrecognized item

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.

I think this example now needs more nuance, given what we say later in the updated spec, and what the conformance suite now says. Given that MovieNoExtra is open, a consistent interpretation (and a plain reading of the text below on 270-272) would allow this call. In this PR we have left it as # E? in the conformance suite (lines 60 and 143 of callables_kwargs.py, to allow type checkers to more strictly error on this case if they choose to, but in principle this call is OK.

For clarity, I think we should expand this to show all three cases: closed, open without extra-items, and extra-items, and then clarity that the unknown kwarg is clearly an error in the closed case, clearly OK in the extra-items case, and in-principle OK in the open case (the same extra kwarg could arrive via unpacking a subtype), but type checkers may still choose to error if the unknown kwarg is given explicitly.

Comment thread docs/spec/callables.rst

from typing import TypedDict, Unpack

class Movie(TypedDict):

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.

Some of the text below is misleading with an open TypedDict. I think we should avoid getting into that upfront, but we should maybe use a closed TypedDict for this initial example, and then get into the subtleties with an open TypedDict later?)

Comment thread docs/spec/callables.rst

Assignment
^^^^^^^^^^
Assignment and Override

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.

This section is ~250 lines long and keeps expanding and getting harder to understand. I also think it still fails to actually describe correct behavior, or what type checkers actually do (see comment below).

I think we should replace this entire section with a totally different (and much simpler) explanation, where we clearly define how **kwargs: Unpack[TD] de-sugars to a "normal" signature, and then just say that all callable assignability rules follow directly from assignability of the de-sugared signatures.

I think the de-sugaring rules are actually quite simple:

  1. turn all required TD fields into required keyword-only parameters, with the type of the field
  2. turn all non-required TD fields into defaulted keyword-only parameters, with the type of the field
  3. add **kwargs: type-of-extra-items for non-closed TD, using object for open TD without an explicit extra-items type

I think that translation gives the intended results, and can do so more clearly with many fewer words, while resolving problems with the current wording.

Comment thread docs/spec/callables.rst
Comment on lines 248 to 249
parameter and the destination function's ``TypedDict`` is :term:`assignable` to
the source function's ``TypedDict`` and the rest of the parameters are

@carljm carljm Nov 25, 2026 •

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.

Here's an illustration of why I think we should re-word this section to specify this via de-sugaring instead. This sentence says that f: TakesInt = takes_object should not be allowed in this example, but it is a safe assignment, and all type checkers actually allow it:

from typing import Protocol, Unpack, TypedDict

class IntArgs(TypedDict, closed=True):
    x: int

class ObjectArgs(TypedDict, closed=True):
    x: object

class TakesInt(Protocol):
    def __call__(self, **kwargs: Unpack[IntArgs]) -> None: ...

def takes_object(**kwargs: Unpack[ObjectArgs]) -> None:
    kwargs["x"] = "hello"

f: TakesInt = takes_object  # The two rules disagree here.

args: IntArgs = {"x": 42}
f(**args)
assert args["x"] == 42  # the mutation in `takes_object` is not visible here

Instances of IntArgs are not assignable to instances of ObjectArgs, because mutability makes the field type of x invariant. According to the wording here, this non-assignability of the TypedDict types would make the assignment f: TakesInt = takes_object invalid. But this field invariance is not relevant to unpacking, since unpacking creates a fresh dictionary; mutations in the function are not visible in the caller's dict.

The de-sugaring version of the spec would allow this: we de-sugar TakesInt to (*, x: int) -> None and takes_object to (*, x: object) -> None -- the latter signature is assignable to the former.

All type-checkers already accept f: TakesInt = takes_object, which means that the current wording here describes a behavior that is neither correct nor actually implemented by any type checker.

meta-codesync Bot pushed a commit to pyrefly-org/pyrefly that referenced this pull request Nov 26, 2026
Summary:
Adds 2 more test cases for David Halter's comments on python/typing#2338 (comment)

In the following excerpt below (see linked comment for context)

```
if bool():
    a1 = a2  # (1) This should error
else:
    a2 = a1  # (2)
```

Pyrefly currently does not error on 1; this PR also fixes that behavior

The PR only adds one rule: the target's extra-kwarg type must also be assignable to every source keyword parameter the target doesn't name.

The actual delta is larger because Claude found a simpler representation of the rules that uses fewer match cases

- [x] I am a human, and I fully understand the code I am submitting.

Pull Request resolved: #5756

Test Plan:
test.py

wait for primer

Reviewed By: stroxler

Differential Revision: D134402139

fbshipit-source-id: ef9f4874b84efb389263ff57c72367555f0b7f93
@yangdanny97

Copy link
Copy Markdown
Contributor Author

addressed the smaller comments for now, will look at the bigger suggested rewrites tomorrow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

topic: conformance tests Issues with the conformance test suite topic: typing spec For improving the typing spec

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants