Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: problem with lambda / closures (http://www.velocityreviews.com/forums/t707197-re-problem-with-lambda-closures.html)

Terry Reedy 11-30-2009 10:53 PM

Re: problem with lambda / closures
 
Benjamin Kaplan wrote:

> I don't know if anyone considers python's incomplete implementation of
> closures a "feature" but it's documented so it's not really a bug
> either.


I believe Python's implementation of closures is quite complete in 3.x.
In what way do you consider it otherwise? One just has to use the right
syntax. Closures in Python are created by nested function definitions.
Lambda expressions create functions just like def statements and are not
closures and do not create closure unless nested within another function
definition. Thinking otherwise is the OP's mistake.

> I believe there is a trick with default arguments to get this
> to work, but I don't use lambdas enough to remember it.


One can simulate closures by giving an un-nested function a default
argument. This has nothing to do with whether the function is defined by
a lambda expression or a def statement.

Terry Jan Reedy



Jussi Piitulainen 12-01-2009 12:20 PM

Re: problem with lambda / closures
 
Terry Reedy writes:

> definitions. Lambda expressions create functions just like def
> statements and are not closures and do not create closure unless
> nested within another function definition. Thinking otherwise is


Seems quite closed in the top level environment to me:

Python 2.3.4 (#1, Jul 16 2009, 07:03:37)
>>> k = 'outer'
>>> f = lambda : k
>>> def test():

... k = 'inner'
... return f()
...
>>> test()

'outer'
>>> k = 'thing'
>>> test()

'thing'

Terry Reedy 12-01-2009 09:50 PM

Re: problem with lambda / closures
 
Jussi Piitulainen wrote:
> Terry Reedy writes:
>
>> definitions. Lambda expressions create functions just like def
>> statements and are not closures and do not create closure unless
>> nested within another function definition. Thinking otherwise is

>
> Seems quite closed in the top level environment to me:
>
> Python 2.3.4 (#1, Jul 16 2009, 07:03:37)
> >>> k = 'outer'
> >>> f = lambda : k
> >>> def test():

> ... k = 'inner'
> ... return f()
> ...
> >>> test()

> 'outer'
> >>> k = 'thing'
> >>> test()

> 'thing'


I used closure in the same sense as the OP, who would have expected the
last result to be 'outer', not 'thing'. Runtime lookup in the lexically
defined global namespace is normal function behavior, not special
closure behavior as most people mean is.

Terry Jan Reedy



All times are GMT. The time now is 10:51 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.