lambda closure question

Carl Banks invalidemail at aerojockey.com
Mon Feb 21 06:26:57 EST 2005


jfj wrote:
> The costly extra feature is this:
> ###############
>   def foo():
>      def f():
>         print x
>      x=1
>      f()
>      x=2
>      f()
>      return f
> foo()()
> #############
> which prints '1 2 2'
>
> The fractal code runs a little _slower_ because of this ability.
> Although the specific program does not take advantage of it!

True, in this case.  (Although it's not that much slower; I think it's
only one extra dereference per access plus a little overhead.)  But try
to extend your mind a bit and imagine that the recursive nested
function is called as part of a larger routine.  Say, for example,
something that seeks a certain shape for the fractal.

. def ifs(transformations,maxdepth):
.     def add_point(...):
.         ...
.     def test_shape():
.         ...
.     while True:
.         add_point(0,0,0,0)
.         x = test_shape()
.         if x < THRESHOLD:
.             break
.         transformations = adjust(transformation)

transformations gets rebound, so you'd need a reference to it.

I realize that this is getting more and more situationally specific (I
wouldn't yet say contrived, though; I have referenced changing bindings
a few times).  Maybe you have a point.


-- 
CARL BANKS




More information about the Python-list mailing list