Skip to content

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

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

yangdanny97 wants to merge 31 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.

@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 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 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 Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
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

@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 for your patience with multiple iterations here! A few more comments, but this looks much better to me.

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 Resolved

@jorenham jorenham left a comment

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.

Looks good! I just have some minor nits.

Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
@yangdanny97

Copy link
Copy Markdown
Contributor Author

Here's an example where mypy and pyright fail on signatures that should be equivalent using the desugaring rules. The other 4 checkers tracked on the leaderboard accept this example.

from typing import *

class TD(TypedDict):
    x: int

class P(Protocol):
    def __call__(self, *, x: int, **kwargs: object) -> None: ...

def f(**kwargs: Unpack[TD]) -> None: ...

f2: P = f  # OK: f desugars to (*, x: int, **kwargs: object)

They are equivalent, but I wonder if we should allow type checkers to optionally error here, like how checkers can already error when explicitly passing unknown keyword arguments to a function with open TypedDict kwargs.

That would align with the "open TypedDicts may contain unknown values but we should discourage it" vibe if that's what we're going for.

@yangdanny97

Copy link
Copy Markdown
Contributor Author

Made some major edits and reorderings to merge/delete some redundancies, and added a bunch of test cases for the desugaring rules and other examples that came up

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

This is looking like a huge improvement to me, and a significant reduction in the size of the spec text. Thank you! A few comments.

Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst Resolved
Comment thread docs/spec/callables.rst
runtime. Even though ``foo`` expects ``kwargs`` of type ``Animal`` it doesn't
matter if it receives additional arguments because it only reads and uses what
it needs completely ignoring any additional values.
Passing a dictionary of type ``dict[str, object]`` as a ``**kwargs`` argument

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 know this wording predates the PR, but I think the blanket rule here conflicts with the new desugaring rules. For example,

class Bag(TypedDict, extra_items=object):
    pass

def f(**kwargs: Unpack[Bag]) -> None: ...

def forward(d: dict[str, object]) -> None:
    f(**d)  # OK

f desugars to def f(**kwargs: object) -> None, so this is safe. All the checkers I tried that support extra_items accept it.

Could we drop the blanket prohibition, explain why dict[str, object] doesn't work for the particular Movie example below, and (maybe? I don't feel strongly) add a positive test like this one?

@yangdanny97 yangdanny97 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The following example without extra_items would pass as well since f desugars to def f(x: object, y: object) -> None, which can normally be called with an unpackeddict[str, object].

from typing import TypedDict, Unpack

class Bag(TypedDict):
    x: object
    y: object

def f(**kwargs: Unpack[Bag]) -> None: ...

def forward(d: dict[str, object]) -> None:
    f(**d)  # OK

If the desired behavior comes naturally as a consequence of desugaring and no extra rules need to be applied, we should just delete the whole section, since it basically contains 1) the wrong rule and 2) "behavior might vary across type checkers"

WDYT?

Comment thread conformance/tests/callables_kwargs.py Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved
Comment thread conformance/tests/callables_kwargs.py Resolved
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