[Tutor] Bitten by lexical closures

Python python at venix.com
Wed May 3 20:49:30 CEST 2006


On Wed, 2006-05-03 at 14:00 +0200, Igor wrote:
> Hi.
> 
> And I thought I understood python pretty well. Until I got hit by this:
> 
> >>> def f(x):
> ...   print x
> 
> >>> cb = [lambda :f(what) for what in "1234"]
> >>> for c in cb:c()
> 4
> 4
> 4
> 4

>>> cb = [(lambda x=what:f(x)) for what in "1234"]
>>> cb[0]()
1

A variable from the enclosing scope is normally only evaluated when
used, that is when the closure is called.  To capture a "transient"
value, you need to explicitly pass it into the closure.  I've gotten
burned on this more than once.

(snipped)
> Regards,
> Igor
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:  603-653-8139
fax:    320-210-3409
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list