can this be done without eval/exec?

Schüle Daniel uval at rz.uni-karlsruhe.de
Wed Apr 26 22:27:28 EDT 2006


>> are there other solutions to this problem
>> without use of eval or exec?
>>
> 
> Using a factory function & closures instead of lambda:

 >>> def a(x):
...     def b():
...             return x
...     return b
...
 >>> lst=[]
 >>> for i in range(10):
...     lst.append(a(i))
...
 >>> lst[0]()
0
 >>> lst[1]()
1
 >>> lst[9]()
9
 >>>

yes this works
I was playing a little more with this idea
and got into the next trouble :)

 >>> cnt=0
 >>> def a():
...     def b():
...             return cnt
...     global cnt
...     cnt += 1
...     return b
...
 >>> lst=[]
 >>> for i in range(10):
...     lst.append(a())
...
 >>> lst[0]()
10
 >>> lst[1]()
10
 >>>

I figured out what was wrong, here is corrected version

 >>> cnt = 0
 >>> def a():
...     global cnt
...     tmp = cnt
...     def b():
...             return tmp
...     cnt += 1
...     return b
...
 >>> lst=[]
 >>> for i in range(10):
...     lst.append(a())
...
 >>> lst[0]()
0
 >>> lst[1]()
1
 >>>

Regards, Daniel



More information about the Python-list mailing list