471,347 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

Callback scoping

Dan
So, I think I understand what python's scoping is doing in the
following situation:
>>x = [ lambda: ind for ind in range(10) ]
x
[<function <lambdaat 0x00BEC070>, <function <lambdaat 0x00BEC7F0>,
<function <lambdaat 0x00BECA70>, <function <lambdaat 0x00C1EBF0>,
<function <lambdaat 0x00C1EE30>, <function <lambdaat 0x00C228F0>,
<function <lambdaat 0x00C228B0>, <function <lambdaat 0x00C28730>,
<function <lambdaat 0x00C286F0>, <function <lambdaat 0x00C287F0>]
>>x[0]()
9
>>x[5]()
9
>>x[9]()
9
>>ind
9
>>ind = 2
x[0]()
2
>>>
But, I'm wondering what is the easiest (and/or most pythonic) way to
get the behavior I want? (If you haven't guessed, I want a list of (no
parameter) functions, each of which returns its index in the list.)

-Dan

Jul 5 '07 #1
2 928
On Thu, 05 Jul 2007 19:14:07 +0000, Dan wrote:
So, I think I understand what python's scoping is doing in the
following situation:
>>>x = [ lambda: ind for ind in range(10) ]

[…]

But, I'm wondering what is the easiest (and/or most pythonic) way to
get the behavior I want? (If you haven't guessed, I want a list of (no
parameter) functions, each of which returns its index in the list.)
Default arguments are evaluated when the function is defined:

In [15]: x = [lambda x=i: x for i in xrange(10)]

In [16]: x[0]()
Out[16]: 0

In [17]: x[5]()
Out[17]: 5

Ciao,
Marc 'BlackJack' Rintsch
Jul 5 '07 #2
Dan <th********@gmail.comwrote:
So, I think I understand what python's scoping is doing in the
following situation:
>x = [ lambda: ind for ind in range(10) ]

But, I'm wondering what is the easiest (and/or most pythonic) way to
get the behavior I want? (If you haven't guessed, I want a list of (no
parameter) functions, each of which returns its index in the list.)
This is the traditional way :-
>>x = [ lambda ind=ind: ind for ind in range(10) ]
x[0]()
0
>>x[2]()
2
>>x[9]()
9
>>>
--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jul 5 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by Ian McMeans | last post: by
2 posts views Thread by David Stockwell | last post: by
2 posts views Thread by Robert M. Gary | last post: by
4 posts views Thread by Joel Gordon | last post: by
9 posts views Thread by NevilleDNZ | last post: by
17 posts views Thread by Chad | last post: by
3 posts views Thread by SPECTACULAR | last post: by

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.