[Python-projects] PyLint: scope of variable of list comprehension

Marc 'BlackJack' Rintsch marc at rintsch.de
Wed Jul 19 21:25:07 CEST 2006


On Wednesday 19 July 2006 20:41, Maarten ter Huurne wrote:
> Hi,
>
> If I run PyLint on this program:
> ===
> l = [n for n in range(10)]
> def f():
>         n = 2
>         return n
> ===
>
> It says:
> ===
> W0621:  3:f: Redefining name 'n' from outer scope (line 1)
> ===
>
> The same happens if I use a generator expression, like this:
> ===
> l = list(n for n in range(10))
> ===
>
> But if I run this code in Python, there is no variable named "n" in
> the global scope. So it seems that in this respect, the "for" of a
> list comprehension / generator expression is different than the "for"
> statement.

This is only true for generator expressions.  With list comprehensions 
the name is "leaking"::

 In [63]: n
 ------------------------------------------------------------------
 exceptions.NameError             Traceback (most recent call last)

 /home/marc/<ipython console>

 NameError: name 'n' is not defined

 In [64]: l = [n for n in range(10)]

 In [65]: n
 Out[65]: 9

Ciao,
	Marc 'BlackJack' Rintsch
-- 
“From the programmer's perspective, indentation implies
 program flow in nearly *all* modern languages.  The
 difference is that in Python the compiler believes you.”
                                  -- Dave Brueck in c.l.p
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 191 bytes
Desc: not available
Url : http://lists.logilab.org/pipermail/python-projects/attachments/20060719/16e2db6a/attachment.pgp


More information about the Python-Projects mailing list