Early and late binding [was Re: what does 'a=b=c=[]' do]

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Dec 23 17:32:15 EST 2011


On Sat, 24 Dec 2011 02:55:41 +1100, Chris Angelico wrote:

> On Sat, Dec 24, 2011 at 2:49 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> To fake early binding when the language provides late binding, you
>> still use a sentinel value, but the initialization code creating the
>> default value is outside the body of the function, usually in a global
>> variable:
>>
>>    _DEFAULT_Y = []  # Private constant, don't touch.
>>
>>    def func(x, y=None):
>>        if y is None:
>>            y = _DEFAULT_Y
>>        ...
>>
>> This separates parts of the code that should be together, and relies on
>> a global, with all the disadvantages that implies.
> 
> A static variable (in the C sense) would make this just as clean as the
> alternative. In Python, that could be implemented as an attribute of the
> function object. Oh looky here... that's how default arguments are
> implemented. :)

Yes. But having to manage it *by hand* is still unclean:

* you still have to assign the default value to the function assignment 
outside the function, which is inelegant; 

* if you rename the function, the internal lookup func.default_value will 
fail.

I'm not saying it can't be done. I'm just saying that the status quo is 
cleaner and more elegant, and if you want late binding, there is a 
simple, obvious, elegant idiom to get it.



-- 
Steven



More information about the Python-list mailing list