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

Add the iter() builtin to checker C407 #152

Closed
sauravsrijan opened this issue May 20, 2019 · 9 comments
Closed

Add the iter() builtin to checker C407 #152

sauravsrijan opened this issue May 20, 2019 · 9 comments

Comments

@sauravsrijan
Copy link

iter()

Example:

even_iterator = iter([i for i in range(1,100) if i%2 == 0])

This can be directly written as:

even_iterator = iter(i for i in range(1,100) if i%2 == 0)
@sauravsrijan sauravsrijan changed the title Add the iter() builtint to checker C407 Add the iter() builtin to checker C407 May 20, 2019
@adamchainz
Copy link
Owner

I think there might be a subtle change in the possible exceptions thrown as per #59

@adamchainz
Copy link
Owner

See also #58

@sauravsrijan
Copy link
Author

Oh! Alright.

But for the existing cases in C407, why are they raised only for list comprehension?
Aren't they valid for different comprehensions too? example: set comprehension

@adamchainz
Copy link
Owner

They probably are, PR's welcome. If you make a PR please ensure you add a changelog note, update the documentation, and create tests.

@joaoe
Copy link

joaoe commented Jan 19, 2020

iter(<comprehension>) is redundant.
(<comprehension>) is enough and produces a generator.

@adamchainz
Copy link
Owner

You're right, since a generator is its own iterator:

In [3]: (x for x in range(1))
Out[3]: <generator object <genexpr> at 0x106df2e40>

In [4]: iter(x for x in range(1))
Out[4]: <generator object <genexpr> at 0x106df2eb0>

@adamchainz
Copy link
Owner

@sauravsrijan released a fix to your issue in version 3.2.0: https://pypi.org/project/flake8-comprehensions/3.2.0/

As per comments on #58 and #59, I'm closing this issue, since it's not generally safe due to the change in possible raised exception from IndexError to StopIteration.

@joaoe
Copy link

joaoe commented Jan 20, 2020

I'm closing this issue, since it's not generally safe due to the change in possible raised exception from IndexError to StopIteration.

#59 deals with <expr>[0]. This issue is just about a plain iter, which always raises a StopIteration when empty.

>>> next(iter([1 for _ in ""]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(1 for _ in "")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

@adamchainz
Copy link
Owner

You're right!

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

No branches or pull requests

3 participants