Repository navigation
Update unpack TypedDict kwargs forwarding spec + add conformance tests - #2338
yangdanny97 wants to merge 16 commits into
Conversation
|
This issue is nuanced, because many unpacking behaviors in Python are unsafe. If you unpack a 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 We decided to be stricter with 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. |
|
For Pyrefly my current thought is that this would be off-by-default and enabled in strict mode. |
|
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? |
|
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?" |
|
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. |
|
Does it make sense to differentiate between implicitly open and explicitly open ( |
It might. Currently in ty we only apply the extra strictness with |
|
The current TypedDict spec says that In the abstract I'd prefer to treat open TypedDicts similar to ones with |
carljm
left a comment
There was a problem hiding this comment.
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.
carljm
left a comment
There was a problem hiding this comment.
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?
|
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): This is currently not an error in Zuban/Mypy (test is called Another case of callable subtyping that I looked at was this one that might be worth to add: Before my changes to think of non-closed TypedDicts in Unpacks as essentially having (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 I'm also open to the make some of the |
20a9e41 to
770b585
Compare
|
Okay, based on the dsicussion in the forum thread, I've updated the docs and tests to require the error. |
|
I haven't had time to look into @davidhalter's examples yet, will do so when i hvae time |
carljm
left a comment
There was a problem hiding this comment.
Looks good! A few things I noticed inline.
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
|
bump |
|
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. |
|
I intentionally did not check the box, because @yangdanny97 wrote that he wants to look at my examples:
I don't think this has happened yet, I don't find any comments or commits about it. |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1c5c7f4 to
b45c105
Compare
|
Oops my bad, I thought I had addressed it already. Will take a look tn |
|
@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. |
|
Thanks @yangdanny97 |
| Unpacking a TypedDict as keyword arguments | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
There was a problem hiding this comment.
| Unpacking a TypedDict as keyword arguments | |
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | |
| Unpacking a TypedDict as keyword argument types | |
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| @@ -235,10 +235,10 @@ | |||
| f(name="No Country for Old Men", year=2007) # Not OK. Unrecognized item | |||
There was a problem hiding this comment.
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.
|
|
||
| from typing import TypedDict, Unpack | ||
|
|
||
| class Movie(TypedDict): |
There was a problem hiding this comment.
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?)
|
|
||
| Assignment | ||
| ^^^^^^^^^^ | ||
| Assignment and Override |
There was a problem hiding this comment.
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:
- turn all required TD fields into required keyword-only parameters, with the type of the field
- turn all non-required TD fields into defaulted keyword-only parameters, with the type of the field
- add
**kwargs: type-of-extra-itemsfor non-closed TD, usingobjectfor 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.
| parameter and the destination function's ``TypedDict`` is :term:`assignable` to | ||
| the source function's ``TypedDict`` and the rest of the parameters are |
There was a problem hiding this comment.
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 hereInstances 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.
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
|
addressed the smaller comments for now, will look at the bigger suggested rewrites tomorrow |
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:
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.