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,136
  • 2
  • 16
  • 38
Rick supports Monica
  • 38,813
  • 14
  • 65
  • 113

0 Answers0