Late-binding of function defaults (was Re: What is a function parameter =[] for?)

Ian Kelly ian.g.kelly at gmail.com
Sat Nov 21 10:01:05 EST 2015


On Sat, Nov 21, 2015 at 1:46 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Nov 21, 2015 at 7:38 PM, Todd <toddrjen at gmail.com> wrote:
>> Rather than a dedicated syntax, might this be something that could be
>> handled by a built-in decorator?
>>
>> Maybe something like:
>>
>> @late_binding
>> def myfunc(x, y=[]):
>
> No, it can't; by the time the decorator runs, the expression has
> already been evaluated. Without syntax, this can only be done with
> gross hacks like lambda functions.
>
> It could be done thus:
>
> @late_binding
> def myfunc(x, y=lambda: []):
>
> and then the decorator could wrap the function. I'm not entirely sure
> I could implement it reliably, but even leaving that aside, having to
> put "lambda:" in front of everything is pretty ugly.

Note that "lambda: []" can also be spelled "list".



More information about the Python-list mailing list