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:
- Why are the
locals()at the point of assignment ofbarnot passed to the comprehension? (The "class definition" scope behaves a lot like any other scope otherwise (even allowingifstatements and such) so this surprised me.) - Is there an alternative way to reference
fooin the comprehension? (Note thatX.fooalso causes aNameErrorasXis not defined at that point.)
I've tested this on Python 3.8, 3.9 and 3.10 and all behave identically.
One workaround I have come up with involves replacing the list comprehension with a
forloop:but I am still interested in more direct answers to the questions raised.