Reputation: 4576
Say I define some class property based on another:
class X:
foo = 42
bar = foo + 5
# X.bar == 47
this works fine. However, foo
is not available if I use a list (or dict, etc.) comprehension:
class X:
foo = 42
bar = [foo + i for i in range(3)]
# NameError: name 'foo' is not defined
This raises two questions:
locals()
at the point of assignment of bar
not passed to the comprehension? (The "class definition" scope behaves a lot like any other scope otherwise (even allowing if
statements and such) so this surprised me.)foo
in the comprehension? (Note that X.foo
also causes a NameError
as X
is not defined at that point.)I've tested this on Python 3.8, 3.9 and 3.10 and all behave identically.
Upvotes: 1
Views: 39
Reputation: 4576
One workaround I have come up with involves replacing the list comprehension with a for
loop:
class X:
foo = 42
bar = []
for i in range(3):
bar.append(foo + i)
# X.bar == [42, 43, 44]
but I am still interested in more direct answers to the questions raised.
Upvotes: 1