default value in __init__

Aaron "Castironpi" Brady castironpi at gmail.com
Sun Oct 12 01:07:37 EDT 2008


On Oct 10, 12:30 pm, Duncan Booth <duncan.bo... at invalid.invalid>
wrote:
> bearophileH... at lycos.com wrote:
> >> I don't think simply re-executing the default argument
> >> expression on each call works either: that would confuse at least as
> >> many people as the current system.
>
> > May I ask you why? I think I don't agree, but I am not sure.
>
(snip)
> I wonder whether it is the way the default argument expressions are
> embedded inside the function that causes the confusion? If for example
> default arguments were defined like this:
>
> class C:
>   @default(d={})
>   def __init__(self, i=10, d):
>     self.d = d
>     self.i = i
>
> would moving the expression before the 'def' make people less inclined to
> be suprised that the object is shared?

You could of course define a wrapper to do call-time assignment:

@calltime( d= dict, e= tuple )
def foo( self, d, e ):

If this decorator appeared in the standard library, newbies would be
able to stumble upon it.

I don't think either semantic is more obvious from the syntax alone.
It could mean either thing just as reasonably, and if Python defined
the opposite, we'd be getting opposite complaints.

On one hand, note that the return statement does not follow the same
convention:

>>> def f(): return [ 0, 1 ]
...
>>> f().append( 2 )
>>> f()
[0, 1]

It constructs a new object each time.  In light of this, the burden of
proof could even fall on Python for the inconsistency.  That is,
assuming that it's well- and always defined.



More information about the Python-list mailing list