Skip to content

Correctly narrow types for tuple[type[X], ...]#15691

Merged
sobolevn merged 3 commits intomasterfrom
issue-15443
Jul 29, 2023
Merged

Correctly narrow types for tuple[type[X], ...]#15691
sobolevn merged 3 commits intomasterfrom
issue-15443

Conversation

@sobolevn
Copy link
Copy Markdown
Member

@sobolevn sobolevn commented Jul 16, 2023

flatten_types forgot about the second way we represent tuple inside.

Closes #15443

@github-actions

This comment has been minimized.

@sobolevn
Copy link
Copy Markdown
Member Author

tuple[type, ...] is an interesting corner case. Will check it.

@github-actions

This comment has been minimized.

@sobolevn
Copy link
Copy Markdown
Member Author

Analyzing primer output: the only idea that I have right now is that previosly it was Any.

@sobolevn sobolevn requested review from JukkaL and ilevkivskyi July 28, 2023 09:34
if isinstance(t, TupleType):
return [b for a in t.items for b in flatten_types(a)]
elif is_named_instance(t, "builtins.tuple"):
return [t.args[0]]
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why is it correct to use all args in former case but just first arg in second case?

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.

Because tuple has only one arg. FWIW the only real question here is whether we need to recurse, i.e. also support:

  • tuple[tuple[type[A], type[B]], ...]
  • tuple[tuple[type[A], ...], ...]

But TBH I don't really care, because it would be a corner case to already rare special case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I've decided not to, because this can be quite complex / slow with no real users asking for it.

Co-authored-by: Ilya Priven <ilya.konstantinov@gmail.com>
@sobolevn
Copy link
Copy Markdown
Member Author

Thanks @ilevkivskyi and @ikonst for the review :)

@github-actions
Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

pandas (https://github.com/pandas-dev/pandas)
+ pandas/core/arrays/datetimelike.py:595: error: Argument 1 to "Timestamp" has incompatible type "object"; expected "integer[Any] | float | str | date | datetime | datetime64"  [arg-type]

@sobolevn sobolevn merged commit da1853f into master Jul 29, 2023
@sobolevn sobolevn deleted the issue-15443 branch July 29, 2023 08:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Variable-length tuple doesn't narrow in isinstance

3 participants