I have a problem with the namespaces defined in the nested functions. Consider the following code:
def fun1():
CHARS = ['C','H','A','R','S']
def fun2():
C = 1
H = 2
A = 3
R = 4
S = 5
# just for warp-up, to ensure oneliners indeed work
a_list = [c for c in CHARS]
# the following structure works: makes [1,2,3,4,5]
eval_list = []
for c in CHARS:
eval_list.append(eval(c))
# this doesn't work. why?
oneliner_eval_list = [eval(c) for c in CHARS] # NameError: name 'C' is not defined
print('func2 ran without problem')
fun2()
print('func1 ran without problem')
fun1()
When I run this the oneliner for loop cannot find the CHARS
in the local namespace and thus goes one level up and finds CHARS
in the enclosed namespace (of fun1
). As it does so, however, it forgets its own namespace and cannot find C
.
- Why is that?
- Why the multi-line for loop doesn't have such a problem?
I use Python3.