Optional parameter object re-used when instantiating multiple objects

George Sakkis george.sakkis at gmail.com
Sun Nov 16 14:02:55 EST 2008


On Nov 16, 8:28 am, Steve Holden <st... at holdenweb.com> wrote:
>
> > +1. Understanding and accepting the current behavior (mainly because
> > of the extra performance penalty of evaluating the default expressions
> > on every call would incur) is one thing, claiming that it is somehow
> > natural is plain silly, as dozens of threads keep showing time and
> > time again. For better or for worse the current semantics will
> > probably stay forever but I wish Python grows at least a syntax to
> > make the expected semantics easier to express, something like:
>
> > def foo(bar=`[]`):
> >     bar.append(6)
>
> > where `expr` would mean "evaluate the expression in the function
> > body". Apart from the obvious usage for mutable objects, an added
> > benefit would be to have default arguments that depend on previous
> > arguments:
>
> Would you also retain the context surrounding the function declaration
> so it's obvious how it will be evaluated, or would you limit the default
> values to expressions with no bound variables?

No, all expressions would be allowed, and the semantics would be
identical to evaluating them in the function body; not context would
be necessary.

> > def foo(x, y=`x*x`, z=`x+y`):
> >     return x+y+z
>
> > as opposed to the more verbose and less obvious current hack:
>
> > def foo(x, y=None, z=None):
> >     if y is None: y = x*x
> >     if z is None: z = x+y
> >     return x+y+z
>
> "Less obvious" is entirely in the mind of the reader.

Without documentation or peeking into the function body, a None
default conveys little or no information, so I don't think it's just
in the mind of the reader. Do you find the following less obvious than
the current workaround ?

from datetime import date
from timedelta import timedelta

def make_reservation(customer,
                     checkin=`date.today()`,
                     checkout=`checkin+timedelta(days=3)`):
   ...


> However I can see
> far more justification for the behavior Python currently exhibits than
> the semantic time-bomb you are proposing.

I didn't propose replacing the current behavior (that would cause way
too much breakage), only adding a new syntax which is now invalid, so
one would have to specify it explicitly.

George



More information about the Python-list mailing list