1

Say I have some function:

def f(x):
    return x

...and some class definition using it, like so:

class Cgood():
    x = None
    y = f('foo')

This works fine:

>>> Cgood().y
'foo'

However, if I try to do something like this:

class Cbad():
    x = None
    y = [f(x) for _ in 'abcdefg']

We get an error:

NameError: name 'x' is not defined

Why is x not available in the scope of the list comprehension? Is there some other way to access x? The only way I see is ditching the list comp and resorting to a normal for loop.

EDIT: I am on Python 3.6.2

jasonharper
  • 9,450
  • 2
  • 18
  • 42
Rick
  • 43,029
  • 15
  • 76
  • 119
  • List comprehension or `for` loop both have no own scope, so Cbad should be working like Cgood do. – Alex Pertsev Jul 31 '17 at 16:40
  • @A.Haaji I agree. Sadly, it doesn't. – Rick Jul 31 '17 at 16:41
  • 1
    i just tried to run your example and i got `Out[3]: [None, None, None, None, None, None, None]` for `In [3]: Cbad.y` – Alex Pertsev Jul 31 '17 at 16:42
  • Isn't it like there must be an operation of the iterator variable on the left side of the for-in loop and not some other variable? – Aakash Verma Jul 31 '17 at 16:44
  • 1
    Also check the explanation under: https://docs.python.org/3.6/reference/executionmodel.html#resolution-of-names – Ashwini Chaudhary Jul 31 '17 at 16:46
  • Good lord I swear I searched before posting this! Thanks for the link @AshwiniChaudhary. – Rick Jul 31 '17 at 16:47
  • In Python 3, list comprehensions are now implemented with a function (which has its own scope) that is called to produce the list value. This makes them work the same as generator expressions, – Kallz Jul 31 '17 at 16:47

0 Answers0