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

Chris Angelico rosuav at gmail.com
Sat Nov 21 03:46:17 EST 2015


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.

ChrisA



More information about the Python-list mailing list