Callback scoping

D

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 <lambda> at 0x00BEC070>, <function <lambda> at 0x00BEC7F0>,
<function <lambda> at 0x00BECA70>, <function <lambda> at 0x00C1EBF0>,
<function <lambda> at 0x00C1EE30>, <function <lambda> at 0x00C228F0>,
[QUOTE= said:
x[0]() 9
x[5]() 9
x[9]() 9
ind 9
ind = 2
x[0]() 2
[/QUOTE]

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
 
M

Marc 'BlackJack' Rintsch

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
 
N

Nick Craig-Wood

Dan said:
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
>>>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top