[code-quality] Warn on list comprehension variables used outside list comprehensions?

Ian Cordasco graffatcolmingov at gmail.com
Wed Nov 26 15:30:34 CET 2014


On Tue, Nov 25, 2014 at 11:41 PM,  <code-quality.wting at xoxy.net> wrote:
> Python binds list comprehension variables to the local scope which has
> caused some subtle bugs. Is it possible to add a warning for this in
> pyflakes? I haven't implemented it yet, but here are the example
> tests:
>
> def test_listCompVariableUsedOutsideListComp(self):
>     """
>     Test that a variable defined in a list comprehension is not used
>     outside of the list comprehension.
>     """
>     self.flakes('''
>     [x for x in range(3)]
>     print x
>     ''', m.VariableUsedOutsideListComp)
>     self.flakes('''
>     [x for x in range(3)]
>     [x for _ in range(3)]
>     ''', m.VariableUsedOutsideListComp)
>
>
> def test_listCompVariableAllowReuse(self):
>     """
>     Test that list comprehension variables are allowed to be reused if
>     redefined.
>     """
>     self.flakes('''
>     [x for x in range(3)]
>     [x for x in range(3)]''')
>
>
> - William

The trick here would be ensuring this only applies to Python 2. Take
for example the following on Python 3:

    [x for x in range(3)]
    print(x)

You will get a NameError because x is undefined outside the list
comprehension. Further, given that PyFlakes operates on the AST
generated for the code, this shouldn't be very difficult, but I'm not
sure how you were thinking of adding this.

With that said, the ultimate decision would fall to Florent and the
other maintainer(s) of PyFlakes.

Cheers,
Ian


More information about the code-quality mailing list