Allow type checkers to infer more precise types for tuples#2194
Allow type checkers to infer more precise types for tuples#2194davidhalter wants to merge 4 commits intopython:mainfrom
Conversation
This is consisent with the latest changes where f(1) could either be an
int or a Literal[1]
def f[T](x: T) -> T: ...
assert_type(f(1), int)
# or
assert_type(f(1), Literal[1])
The same is possible with tuples:
def f[*Ts](*x: *Ts) -> tuple[*Ts]: ...
assert_type(f(1), tuple[int])
# or
assert_type(f(1), tuple[Literal[1]])
|
|
||
|
|
||
| assert_type(args_to_tuple(1, "a"), tuple[int, str]) | ||
| assert_type(args_to_tuple(1, "a"), tuple[int, str]) # E[args_to_tuple] |
There was a problem hiding this comment.
To avoid the two options, could we put this in a function that takes args of type int and str? Then tuple[int, str] would be unambiguously right.
There was a problem hiding this comment.
Thanks Jelle, that's a really good idea, it also feels more readable this way for people that are not used to the special # E[...] comments.
I pushed this. This makes Mypy pass generics_typevartuple_callable.py again and doesn't really change anything other than Zuban passing the tests with its latest release.
There was a problem hiding this comment.
Hmm, I weakly prefer the version prior to c1ffe96. The new version could pass even if the type checker completely fails to solve the TypeVarTuple and just falls back to *tuple[Any, ...] for its inference of *Ts. The version with the # E[] tagged errors was precise
There was a problem hiding this comment.
Didn't think about that. That's obviously a problem. I'm happy to revert...
There was a problem hiding this comment.
I meant something like this:
def func(x: int, y: str):
assert_type(args_to_tuple(x, y), tuple[int, str])
I agree the current version is worse.
There was a problem hiding this comment.
@AlexWaygood @JelleZijlstra Thank you for the good feedback. Kind of stupid of me to not think of this in the first place. I think the change is now completely uncontroversial.
…ultiple assert_types depending on different type inference
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
AlexWaygood
left a comment
There was a problem hiding this comment.
this makes sense to me, thanks!
This is consisent with the latest changes where
f(1)could either be an int or aLiteral[1]The same is possible with tuples:
Mypy fails the test
generics_typevartuple_callable.pynow, because it doesn't error on any of the assert_type below:This is also how Zuban used to work, but I think it's better to be precise here and it should probably fail one of the two (like Eric suggested in #2178 (comment)).
Ran the automated tests again. A few changes: