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

Lie Ryan lie.1296 at gmail.com
Sat Dec 24 23:12:27 EST 2011


On 12/24/2011 07:25 PM, Steven D'Aprano wrote:
>> I'd use a function attribute.
>>
>> def func(x, y=None):
>>    if y is None:
>>      y = func.default_y
>>    ...
>> func.default_y = []
>>
>> That's awkward only if you believe function attributes are awkward.
>
> I do. All you've done is move the default from *before* the function is
> defined to *after* the function is defined, instead of keeping it in the
> function definition. It's still separate, and if the function is renamed
> your code stops working. In other words, it violates encapsulation of the
> function.

Although we can solve that (default being after the function is defined) 
using a simple decorator:

def funcargs(**args):
     def __decorate_with_args(func):
         for k,v in args.items():
             setattr(func, k, v)
         return func
     return __decorate_with_args

Usage:

@funcargs(foo=4)
def bar(baz):
     return baz + bar.foo

et voila, we had just reinvented early binding default argument, with a 
much uglier syntax.




More information about the Python-list mailing list