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

Warn if generator is iterated over more than once #8640

Open
tmke8 opened this issue Apr 6, 2020 · 2 comments
Open

Warn if generator is iterated over more than once #8640

tmke8 opened this issue Apr 6, 2020 · 2 comments

Comments

@tmke8
Copy link
Contributor

tmke8 commented Apr 6, 2020

Somewhat related to #4707

This code currently does not give any warnings:

gen = (3 * x for x in range(10))  # revealed type: Generator[int, None, None]
for i in gen:
    print(i)

for i in gen:
    print(i)

and while this does run, it doesn't do what the programmer expects. Only the first iteration prints anything. The second iteration stops immediately because the generator is already exhausted.

This might be very difficult, but it would be nice if mypy could detect this.

@silviogutierrez
Copy link

This just happened to me yesterday. Would be great to catch it.

However, I think this falls in the realm of unique types, which is about as advanced as type systems go. So I'm not sure mypy will ever land this...[1]

[1] https://en.wikipedia.org/wiki/Uniqueness_type

@JukkaL
Copy link
Collaborator

JukkaL commented Apr 9, 2020

Mypy won't be able to catch all issues like these, but at least simple cases like the same generator being iterated twice in succession in a single scope would be possible to catch.

We might want to do this for all iterables, not just generators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants