[Python-Dev] 2.5 and beyond

jan-python at maka.demon.nl jan-python at maka.demon.nl
Sun Jul 2 13:58:55 CEST 2006


Hi everyone, Even though I'm new on this list I think I've got something
sensible to say on this one. (I've been following this list a bit through the
archives)

Andrew Koenig wrote:
> You seem to be right -- the problem is not that Python is lexically   scoped,
> but that when you define a variable with =, it leaks out into the
> surrounding function scope.

> So maybe what I meant when I asked for lexical scopes was two things:
>
> 1) Every indentation level should be a scope;
> 2) In general, variable definitions should not leak into
>    surrounding scopes.
>
> I realize that (2) is too simplistic.  Someone who writes

I believe the problem has nothing to do with how many scopes a block/function
definition has, but with what the lambda does with the scope it's given.
Currently it remembers the block and looks up the nescessary variables in it
when it's invoked. I think it shoud should have just taken the values of the
needed variables and rememberd those as it's own local variables. So 
the closed
over variables become just local variables initialised to the value 
they have in
the outer scope.

Without having any blocks to be confused about, I think this is
counterintuitive
as well:

>>> x = 1
>>> f = lambda: x
>>> x = 2
>>> g = lambda: x
>>> f()
2
>>> g()
2

I think it should have been:
....
>>> f()
1
>>> g()
2

Using the lambda x=x: x trick gives exactly this behaviour because it
apparently does copy the value of x. As far as I can see it also solves the
>>> for i in range(10):
  ...     a.append(lambda: i)
case, and other similar examples.
(However, this would probably be a to big change for 2.5)



More information about the Python-Dev mailing list