Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Empty Collection Handling with next #12064

Open
max-muoto opened this issue May 30, 2024 · 0 comments · May be fixed by #12065
Open

Empty Collection Handling with next #12064

max-muoto opened this issue May 30, 2024 · 0 comments · May be fixed by #12065

Comments

@max-muoto
Copy link
Contributor

max-muoto commented May 30, 2024

There are some issues when using next when providing an empty collection as a default, let's take this example:

from collections.abc import Iterable


def foo(iter: Iterable[list[int]]) -> None:
    next((item for item in iter if len(item) > 5), [])

This leads to errors in Pyright, as [] is treated as list[unknown]. Pyright Playground.

Here are the current next overloads:

@overload
def next(i: SupportsNext[_T], /) -> _T: ...
@overload
def next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ...

I would propose changing the second one to:

def next(i: SupportsNext[_T], default: _VT | _T, /) -> _T | _VT: ...

This would fix the above issue, as in the case an empty list or othe rcollection Pyright could just infer the type as _T, while not disrupting other cases in which the types differ.

With this change in Pyright:

from typing import reveal_type

def foo(iter: Iterable[list[int]]) -> None:
    result = next((item for item in iter if len(item) > 5), [])
    reveal_type(result) # Revealed type is `list[int]`.
@max-muoto max-muoto changed the title Empty List Default with next Empty Collection with next May 30, 2024
@max-muoto max-muoto changed the title Empty Collection with next Empty Collection Handling with next May 30, 2024
@max-muoto max-muoto linked a pull request May 30, 2024 that will close this issue
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 a pull request may close this issue.

1 participant