This works:
class Foo:
ATTR_1 = [1, 2]
ATTR_2 = [i for i in ATTR_1]
def __init__(self):
print(Foo.ATTR_1, Foo.ATTR_2)
Foo()
It prints [1, 2] [1, 2]
. However, adding a condition to the list comprehension in the third line causes Python to throw a NameError
:
class Foo:
ATTR_1 = [1, 2]
ATTR_2 = [i for i in ATTR_1 if len(ATTR_1) > 0]
def __init__(self):
print(Foo.ATTR_1, Foo.ATTR_2)
Foo()
Traceback:
Traceback (most recent call last):
File "/path/to/tmp.py", line 1, in <module>
class Foo:
File "/path/to/tmp.py", line 3, in Foo
ATTR_2 = [i for i in ATTR_1 if len(ATTR_1) > 0]
File "/path/to/tmp.py", line 3, in <listcomp>
ATTR_2 = [i for i in ATTR_1 if len(ATTR_1) > 0]
NameError: name 'ATTR_1' is not defined
Why is that and how can I work around it? I am using Python 3.6.4.