0

Documentation says that the body of a declared class is executing roughly as exec(body, globals(), namespace). Nevertheless, the following code raises a NameError (global name 'r' is not defined)

class Test:
    r = 3
    l = [i + r for i in range(r)]

while the following code succeeds with the expected result

class Test:
    r = 3
    l = []
    for i in range(r):
        l.append(i + r)

Furthermore, the following code also succeeds, with the expected result

code = """r = 3; l = [i + r for i in range(r)]"""
namespace = {}
exec(code, globals(), namespace)

What are the particularities of list comprehension making the first code raising an error? Is there a way to fix this problem but still keeping the list-comprehension style?

Simon Busard
  • 145
  • 1
  • 5
  • 1
    Did you check that? http://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition – user189 Jul 07 '14 at 09:26
  • Thank you very much. I didn't find this answer before asking my question. Next time, I will search a bit more... – Simon Busard Jul 07 '14 at 09:38

0 Answers0