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

George Sakkis george.sakkis at gmail.com
Mon Oct 13 20:24:27 CEST 2008


On Mon, Oct 13, 2008 at 2:05 PM, Arnaud Delobelle <arnodel at googlemail.com>wrote:

>
> 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


But the whole point of this thread is that this is an abuse of default
arguments since it changes f's signature; f(5,6), f(1), f(y=10) should all
raise TypeError.

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


But this happens only once at decoration time, not every time f is called,
right ?

George
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20081013/a150a07f/attachment.html>


More information about the Python-ideas mailing list