473,395 Members | 1,471 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

can this be done without eval/exec?

Hello group,
lst=[]
for i in range(10): .... lst.append(eval("lambda:%i" % i))
.... lst[0]() 0 lst[1]() 1 lst[9]() 9 lst=[]
for i in range(10): .... exec "tmp = lambda:%i" % i # assignment is not expression
.... lst.append(tmp)
.... lst[0]() 0 lst[1]() 1 lst[9]() 9
and now the obvious one (as I thought at first)
lst=[]
for i in range(10): .... lst.append(lambda:i)
.... lst[0]() 9 i 9


I think I understand where the problem comes from
lambda:i seems not to be fully evalutated
it just binds object with name i and not the value of i
thus lst[0]() is not 0

are there other solutions to this problem
without use of eval or exec?

Regards, Daniel
Apr 27 '06 #1
4 1426
On 4/26/06, Schüle Daniel <uv**@rz.uni-karlsruhe.de> wrote:
Hello group,
>>> lst=[]
>>> for i in range(10): ... lst.append(eval("lambda:%i" % i))
... >>> lst[0]() 0 >>> lst[1]() 1 >>> lst[9]() 9 >>> >>> lst=[]
>>> for i in range(10): ... exec "tmp = lambda:%i" % i # assignment is not expression
... lst.append(tmp)
... >>> lst[0]() 0 >>> lst[1]() 1 >>> lst[9]() 9 >>>
and now the obvious one (as I thought at first)
>>> lst=[]
>>> for i in range(10): ... lst.append(lambda:i)
... >>> lst[0]() 9 >>> i 9 >>>
I think I understand where the problem comes from
lambda:i seems not to be fully evalutated
it just binds object with name i and not the value of i
thus lst[0]() is not 0

are there other solutions to this problem
without use of eval or exec?

Using a factory function & closures instead of lambda:
def maker(x): .... def inner_maker():
.... return x
.... return inner_maker
.... lst = []
for i in range(10): .... lst.append(maker(i))
.... lst[0]() 0 lst[5]() 5 lst[9]() 9


Regards, Daniel
--
http://mail.python.org/mailman/listinfo/python-list

Apr 27 '06 #2
>> 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
Apr 27 '06 #3
Schüle Daniel wrote:
and now the obvious one (as I thought at first)
>>> lst=[]
>>> for i in range(10): ... lst.append(lambda:i)
... >>> lst[0]() 9 >>> i 9 >>>

I think I understand where the problem comes from
lambda:i seems not to be fully evalutated
it just binds object with name i and not the value of i
thus lst[0]() is not 0


The problem is that variables in closures are not bound until the
variable goes out of scope. So each lambda is bound to the final value of i.
are there other solutions to this problem
without use of eval or exec?


The workaround is to use a default argument to bind the current value of i:
In [1]: lst = []

In [2]: for i in range(10):
...: lst.append(lambda i=i: i)
...:
...:

In [3]: lst[0]()
Out[3]: 0

In [4]: lst[5]()
Out[4]: 5

A list comp makes this IMO cleaner:
In [5]: lst = [ lambda i=i: i for i in range(10) ]

In [6]: lst[0]()
Out[6]: 0

In [7]: lst[5]()
Out[7]: 5

Kent
Apr 27 '06 #4
Kent Johnson schrieb:
Schüle Daniel wrote:
and now the obvious one (as I thought at first)
>>> lst=[]
>>> for i in range(10):

... lst.append(lambda:i)
...
>>> lst[0]()

9
>>> i

9
>>>


I think I understand where the problem comes from
lambda:i seems not to be fully evalutated
it just binds object with name i and not the value of i
thus lst[0]() is not 0


The problem is that variables in closures are not bound until the
variable goes out of scope. So each lambda is bound to the final value
of i.

are there other solutions to this problem
without use of eval or exec?


The workaround is to use a default argument to bind the current value of i:
In [1]: lst = []

In [2]: for i in range(10):
...: lst.append(lambda i=i: i)
...:
...:

In [3]: lst[0]()
Out[3]: 0

In [4]: lst[5]()
Out[4]: 5

A list comp makes this IMO cleaner:
In [5]: lst = [ lambda i=i: i for i in range(10) ]

In [6]: lst[0]()
Out[6]: 0

In [7]: lst[5]()
Out[7]: 5

Kent


many thanks for the explaination,
it look much simpler than my solutions too

Daniel
Apr 27 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Ido.Yehieli | last post by:
Hi all, I'm new to c# and .net and I have a few questions I did not manage to find an answer to: 1. what is the equivalent to the "exec" command in python/lisp? meaning: a string is given as...
3
by: Jens | last post by:
Hi, has anyone an idea why the following code does not work. s = """ def a(n): return n*n
6
by: vasudevram | last post by:
Hi group, Question: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? I wrote a function to generate other functions using something like eval("def foo: ....") but...
6
by: dave.g1234 | last post by:
Suppose I have a function in module X that calls eval e.g, X.py _______ Def foo(bar): Eval(bar) _______ Now eval will be called using the default eval(bar,globals(),locals()) and globals...
10
by: TheSaint | last post by:
Hi, It seems to be strange that give me syntax error inside an eval statement. I'm looking at it carefully but I can't see any flaw. Here it's part of the code: for nn in stn_items: value=...
6
by: Stef Mientki | last post by:
hello, I'm trying to make an editor with an integrated Shell. 2+5 7 myvar = 55 myvar 55
16
by: Fett | last post by:
I am creating a program that requires some data that must be kept up to date. What I plan is to put this data up on a web-site then have the program periodically pull the data off the web-site. ...
0
by: Jean-Paul Calderone | last post by:
On Thu, 28 Aug 2008 14:51:57 -0700 (PDT), Fett <fettmanchu@gmail.comwrote: eval and exec are the same. Don't use either with strings from a web page. Try using a simple format for you data, such...
3
by: James Mills | last post by:
On Thu, Oct 9, 2008 at 2:26 PM, Warren DeLano <warren@delsci.comwrote: Yes it does :) I second this. It's far better to use Data Structures rather than Programming Constructs
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.