3

For the following code:

class Test:
    BAR = 'world'
    FOO1 = "%s" % BAR
    FOO2 = ["%s" % BAR for _ in range(1)]

I get the following error:

Traceback (most recent call last):
  File "<redacted>", line 1, in <module>
    class Test:
  File "<redacted>", line 4, in Test
    FOO2 = ["%s" % BAR for _ in range(1)]
  File "<redacted>", line 4, in <listcomp>
    FOO2 = ["%s" % BAR for _ in range(1)]
NameError: name 'BAR' is not defined

Notice from the traceback that the error only occurs when accessing BAR from within a list comprehension - this is very puzzling as I would assume a list comprehension would share the scope it was called from, so I have two questions:

  • why is this happening?
  • is there any way to accomplish this? ie using a class attribute in a list comprehension to declare another class attribute?

This is on CPython 3.9

Michoel
  • 834
  • 5
  • 16
  • 1
    basically the short solution is this: `FOO2 = (lambda bar=BAR: ["%s" % bar for _ in range(1)])()` – Matiiss Nov 01 '21 at 16:28

0 Answers0