Callback scoping

Nick Craig-Wood nick at craig-wood.com
Thu Jul 5 16:30:07 EDT 2007


Dan <thermostat at gmail.com> 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.)

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 <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list