[Python-ideas] Default arguments in Python - the return - running out of ideas but...

Steven D'Aprano steve at pearwood.info
Thu May 14 00:01:32 CEST 2009


On Thu, 14 May 2009 05:18:37 am CTO wrote:

> If you thought not reevaluating function expressions
> was confusing for newbies, wait until you see what making up a new
> kind of yield will do for them.
>
> Why not just push for some decorators that do this to be included in
> stdlib? I see the utility, but not the point of adding extra syntax.

Even if a decorator solution can be made to work, it seems to me that 
the difficulty with a decorator solution is that it is 
all-or-nothing -- you can decorate the entire parameter list, or none 
of the parameters, but not some of the parameters. You can bet that 
people will say they want delayed evaluation of some default arguments 
and compile-time evaluation of others, in the same function definition.

There are work-arounds, of course, but there are perfectly adequate 
work-arounds for the lack of delayed evaluation defaults now, and it 
hasn't stopped the complaints.

I'm going to suggest that any syntax should be applied to the formal 
parameter name, not the default value. This feels right to me -- we're 
saying that it's the formal parameter that is "special" for using 
delayed semantics, not that the default object assigned to it is 
special. Hence it should be the formal parameter that is tagged, not 
the default value.

By analogy with the use of the unary-* operator, I suggest we use a new 
unary-operator to indicate the new semantics. Inside the parameter 
list, &x means to delay evaluation of the default argument to x to 
runtime:

def parrot(a, b, x=[], &y=[], *args, **kwargs):

As a bonus, this will allow for a whole new series of bike-shedding 
arguments about which specific operator should be used. *grin*

Tagging a parameter with unary-& but failing to specify a default value 
should be a syntax error:

def parrot(&x, &y=[]):

Likewise for unary-& outside of a parameter list.

Bike-shedding away... *wink*



-- 
Steven D'Aprano



More information about the Python-ideas mailing list