[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Ways to make a free variable local to a function?

On Tue, Mar 6, 2018 at 8:02 PM, Kirill Balunov <kirillbalunov at gmail.com> wrote:
> 2018-03-05 17:34 GMT+03:00 Chris Angelico <rosuav at gmail.com>:
>> In theory, the CPython bytecode compiler (don't know about other
>> Python implementations) could just add these as constants. They'd then
>> be bound at either compile time or function definition time (by
>> default the former, I think, but the latter would be more useful), and
>> be looked up as quickly as locals. I'm not sure how useful this would
>> be, though.
> With some assumptions, It will be useful for every function call:-)
>> If PEP 572 [1] were to be accepted, you could do something like this:
>> def func(numb):
>>     if ((int as int), (float as float)):
>>         res = []
>>         for i in range(numb):
>>             res.append(int(i) + float(i))
>>         return res
>> Syntactically a bit clunky, but keeps everything inside the function,
>> and DOES create local variables. Not sure it's better than your other
>> options, but it is another option.
> While I'm +0.5 on yours PEP 572 idea, especially in `while` and `if`
> statements, this example is an overuse of the proposed syntax ;-) Also it
> will add an overhead on every function call, and as you said  -
> "Syntactically a bit clunky".

The run-time overhead should be insignificant; this kind of
optimization is done when you're running a tight loop, so it's the run
time of the loop body that dominates the function. That's also why I
do NOT want this to happen at compile time, even though that would be
the easiest. The very latest this should happen is function definition
time; it would be extremely surprising otherwise. And if it happens
once when the function's called, that's usually not going to be much
cost compared to the saving of LOAD_FAST instead of LOAD_GLOBAL in
each iteration of the loop.