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

Arnaud Delobelle arnodel at googlemail.com
Mon Oct 13 20:05:44 CEST 2008


On 13 Oct 2008, at 15:22, George Sakkis wrote:

> On Mon, Oct 13, 2008 at 8:09 AM, Arnaud Delobelle <arnodel at googlemail.com 
> > wrote:
>
> > 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.
>
> Can you expand a bit on that ? Why would it be terribly inefficient  
> and why is it useless ?

When I was saying it was useless, I was talking about my bind  
decorator of course!

It's useless because the above can be written

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

It's inefficient because it works by deconstructing and reconstructing  
the function bytecode.

If I have the time I will post an implementation of your localize  
decorator in CPython later (I think it would be easy, if one ignores  
nonlocal variables in nested functions).

-- 
Arnaud




More information about the Python-ideas mailing list