I am confused about methods combined with list comprehension and the eval
statement. The code below errors on the test7 line with the error NameError: name 'a2' is not defined
.
class test_class(object):
def __init__(self):
pass
@property
def property(self):
return 'test_method_run'
def run():
a2 = test_class()
test3 = eval('a.property')
test4 = [eval('a.property') for i in range(10)]
test5 = eval('a2.property')
test6 = [a2.property for i in range(10)]
test7 = [eval('a2.property') for i in range(10)
a = test_class()
test1 = eval('a.property')
test2 = [eval('a.property') for i in range(10)]
run()
It must have something to do with scope (eval fails in list comprehension). My understanding of scope in python 2 (I have just moved to python 3) was that a
should not be defined within run()
, but a2
is. I'm further confused by the impact of the list comprehension. My expectation was that test2
and test3
lines should fail as a
is not defined with the test
method. Also I expected that if test5
runs OK then test6
and test7
should also be fine.
This error only occurs when eval
is used in a list comprehension within a function... If any of these 3 elements are not present then there is no error. My question is why? I don't feel like I understand it enough to form a better question.