[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake

Arnaud Delobelle arnodel at googlemail.com
Mon Oct 13 14:09:29 CEST 2008


> Since this idea didn't get much steam, a more modest proposal would be to
> relax the restriction on cells: allow the creation of new cells and the
> rebinding of func_closure in pure Python. Then one could explicitly create a
> new scope without any other change in the language through a 'localize'
> decorator that would create a new cell for every free variable (i.e. global
> or value from an enclosing scope) of the function:
>
> lst = []
> for i in range(10):
>    @localize
>    def f(): print i
>    lst.append(f)
>    lst.append(localize(lambda: i**2))
>
> I'd love to be proven wrong but I don't think localize() can be implemented
> in current Python.

I think you probably can in CPython, but that would involve bytecode
introspection and using ctypes.pythonapi.PyCell_New, and it would be
terribly inefficient.  I wrote a similar decorator that takes a
function and bind some of its variables to some values. e.g

@bind(x=40, y=2)
def foo(): return x+y

>>> foo()
42

It's useless of course.

-- 
Arnaud



More information about the Python-ideas mailing list