unexpected behaviour of lambda expression

leonhard.vogt at gmx.ch leonhard.vogt at gmx.ch
Mon Oct 9 14:07:15 CEST 2006


Fredrik Lundh schrieb:

> leonhard.vogt at gmx.ch wrote:
>
> > Please consider that example:
> > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
> > on win32
> > Type "help", "copyright", "credits" or "license" for more information.
> >>>> s = 'foo'
> >>>> f = lambda x: s
> >>>> f(None)
> > 'foo'
> >>>> s = 'bar'
> >>>> f(None)
> > 'bar'
> >>>> del(s)
> >>>> f(None)
> > Traceback (most recent call last):
> >  File "<stdin>", line 1, in ?
> >  File "<stdin>", line 1, in <lambda>
> > NameError: global name 's' is not defined
> >
> > It seems to me, that f is referencing the name s instead of the string
> > object bound to it
>
> that's how lexical scoping works, of course.
>
> if you want to bind to the object instead of the name, use explicit binding:
>
>     f = lambda x, s=s: s
>
> </F>

Thank you, together with the response of Duncan it is clear to me now.
I will use something like
>>> def makefunc(t):
...     return lambda x: t
...
>>> s = 'foo'
>>> f = makefunc(s)
>>> f(None)
'foo'
>>> s = 'bar'
>>> f(None)
'foo'

Leonhard




More information about the Python-list mailing list