Referring to other class properties in comprehension

52 Views Asked by At

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:

  1. Why are the 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.)
  2. Is there an alternative way to reference 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.

1

There are 1 best solutions below

2
On

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.