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

Ian Cordasco graffatcolmingov at gmail.com
Wed Nov 26 15:52:09 CET 2014


On Wed, Nov 26, 2014 at 8:44 AM, Skip Montanaro
<skip.montanaro at gmail.com> wrote:
> On Wed, Nov 26, 2014 at 8:30 AM, Ian Cordasco
> <graffatcolmingov at gmail.com> wrote:
>>
>> 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.
>
> Note that pylint just grew a --py3k flag, which is used when scanning
> Python 2.x code looking for potential problems porting to Python 3.x.
> If pyflakes grew a similar flag, William's proposed check could be
> enabled only when --py3k was given.
>
> Skip

That's not the point of this check. The point of this check is that on
Python 2, the binding to x in the comprehension bleeds outside of the
comprehension scope (into the scope of the print statement) whereas
that doesn't happen on Python 3. William is proposing adding a
warning/error about using bindings created in a comprehension outside
of the scope because it can cause problems. The following on Python 2
will surprise some people:

    x = 10
    [x for x in range(3)]
    print(x + 1)

On Python 2 that will print 3. On Python 3 that will print 11. The
idea is to warn people of the fact that the binding will bleed but to
only do it on Python 2. This has no basis in Python 3.


More information about the code-quality mailing list