default value in __init__

Aaron "Castironpi" Brady castironpi at gmail.com
Thu Oct 16 15:18:49 EDT 2008


On Oct 16, 12:23 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Thu, 16 Oct 2008 17:05:40 +1300, Lawrence D'Oliveiro wrote:
> > In message <01006451$0$20646$c3e8... at news.astraweb.com>, Steven D'Aprano
> > wrote:
>
> >> On Thu, 09 Oct 2008 01:39:30 -0700, kenneth (a.k.a. Paolo) wrote:
>
> >>> On Oct 9, 10:14 am, Christian Heimes <li... at cheimes.de> wrote:
>
> >>>> No, it always contains the default argument because default values
> >>>> are created just ONE TIME
> > <http://effbot.org/pyfaq/why-are-default-values-shared-between-
> objects>...
>
> >>> Wow, it's a very "dangerous" behavior ...
>
> >> No, it's very *useful* behaviour.
>
> > Can you give an example of how useful it is? Something worth the pain of
> > newbies tripping over it every week?
>
> Did you read the effbot's explanation in the link above? He gives two
> examples, memoization and binding of locals.
>
> The second example is especially interesting, because that's also a
> Gotcha for newbies (not just noobs either...), and the solution to that
> specific gotcha is Python's use of define-time binding of default values.
>
snip
> Newbies get confused by this almost as often as by the default value
> semantics, but the simplest solution to this gotcha is to use Python's
> default values:
snip

Both of those are shorthand notations and there are alternative ways
to express both of them.  The alternatives might even be more literal,
that is, less idiomatic, in the language's tokens' semantics.

For the first one, effbot says: 'You could use a global variable
containing a dictionary instead of the default value; it’s a matter of
taste'.  You could also use an attribute of the function, which is an
entry in func_dict.

For the second one, it is more verbose, but you can add an enclosing
lambda or def expression, and call it on the spot.  I'll be honest:
those are plusses, that is pros of the decision, but they aren't that
strong.

> If Python re-evaluated the default value i=i at runtime, the above would
> break.

Not with a mere extra lambda.  The fact that a syntax is an
opportunity to have a behavior does not imply that it should have
one.  The fact that newbies ask about these semantics doesn't imply
that they'd ask about another one just as much.  The fact that these
semantics have these two uses, doesn't imply that the others don't
have more.  Immutable defaults behave identically in both.

> --
> Steven



More information about the Python-list mailing list