When defining a class and assigning it a few class variables, I came across the need to use a class variable I'd already defined to generate another variable, within a list comprehension. Stripped down to the core, my problem is as follows
class Foo():
d = [1, 2, 3, 4, 5, 6, 7, 8]
e = [2 * x for x in range(100)]
# Works as expected
# prints [0, 2, 4, 6, 8, 10, ...]
print(e)
baz = [
e[i] # NameError: 'e' is not defined
for i in d
]
x = Foo()
However, once I get into the comprehension, I get a NameError, telling me that 'e' is not defined
. I know for a fact then when not in a class definition, this works
d = [1, 2, 3, 4, 5, 6, 7, 8]
e = [2 * x for x in range(100)]
baz = [
e[i]
for i in d
]
print(baz) # Works as expected, producing [2, 4, 6, 8, 10...]
So evidently, being in a class-definition scope seems to be messing things up. I've tried prepending e[i]
with self.
and cls.
(admittedly out of desperation) but to no avail.
What am I missing?
Several Google searches haven't yielded anything, but if this is a duplicate and anybody can point me in the right direction I'd be glad.