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

skip at pobox.com skip at pobox.com
Wed Jul 19 21:45:40 CEST 2006


    Maarten> l = [n for n in range(10)]
    Maarten> def f():
    Maarten>         n = 2
    Maarten>         return n

    Maarten> W0621:  3:f: Redefining name 'n' from outer scope (line 1)

    Maarten> The same happens if I use a generator expression, like this:

    Maarten> l = list(n for n in range(10))

    Maarten> But if I run this code in Python, there is no variable named
    Maarten> "n" in the global scope. So it seems that in this respect, the
    Maarten> "for" of a list comprehension / generator expression is
    Maarten> different than the "for" statement.

I think you're mistaken about "n" in the list comprehension case:

    % python
    Python 2.4.2 (#1, Feb 23 2006, 12:48:31)
    [GCC 3.4.1] on sunos5
    Type "help", "copyright", "credits" or "license" for more information.
    >>> lst = [n for n in range(10)]
    >>> lst
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> n
    9
    >>> gen = (m for m in range(10))
    >>> gen
    <generator object at 0x81f342c>
    >>> list(gen)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> m
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'm' is not defined

PyLint should warn you about redefining 'n' in the listcomp case, but not in
the gencomp case.

Skip


More information about the Python-Projects mailing list