python / python/mypy

Warn if generator is iterated over more than once

Open
#8,640 2 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature priority-2-low
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the generator example in the issue and investigate how mypy could identify that the same generator is iterated more than once. Done would be a warning for the second iteration without warning on valid generator use; the issue names no files or tests, so the relevant implementation and regression-test locations must first be identified.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.