Ways to make a free variable local to a function?

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Tue Mar 6 04:35:08 EST 2018


On 03/05/2018 07:44 PM, Terry Reedy wrote:
> On 3/5/2018 9:34 AM, Chris Angelico wrote:
>> On Tue, Mar 6, 2018 at 12:52 AM, Terry Reedy <tjreedy at udel.edu> wrote:
>>> On 3/5/2018 7:12 AM, Kirill Balunov wrote:
>>>> # 1. By passing through local variable's default values
>>>>
>>>>        def func_local_1(numb, _int = int, _float = float, _range = range):
>>>
>>>
>>> You are not required to mangle the names.
>>>
>>> def func_local_1(numb, int = int, float = float, range = range):
>>> ...
>>>
>>
>> Even so, this does mess up the function's signature,
> 
> Which I why I only said that using the original names solves the syntax
> highlighting issue (of marking built-ins as built-ins).
> 
>> leaving your
>> callers wondering if they can call it with some sort of range
>> parameter. (Though in this particular instance, range() is only called
>> once, so it's pretty much useless to try to optimize it.)
>>
>> In theory, the CPython bytecode compiler (don't know about other
>> Python implementations) could just add these as constants.
> 
> Yes, what we really want for this sort of thing are unrebindable local
> constants.  A simple syntax change could do it.
> 
>    def func_local_1(numb; int = int, float = float, range = range):
> 
> The binding after ';' belong in the header because they should be done once.
> 

Ah, I did not really understand initially what Kirill was trying to 
achieve by putting the name binding into the function signature.
Now I do, but I don't think it is a good idea. Sanctioning this with 
dedicated syntax would only make Python more static because for any 
function defined this way, you would lose the ability to alter the 
behavior of that function through changing the global binding after the 
function has been called (in the example above, you could no longer mock 
replace int, float and range on subsequent func_local_1 calls) and I 
don't think this is something that should be encouraged.

Wolfgang





More information about the Python-list mailing list