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?