default value in __init__

Steven D'Aprano steve at
Sat Oct 11 11:41:17 CEST 2008

On Fri, 10 Oct 2008 06:20:35 -0700, bearophileHUGS 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.

x = 100
def foo(a, b=x):
    return a+b

first = foo(1)
x = 101
second = foo(1)

assert first == second

I think people will be rightly surprised that this fails.

>> It would be possible, but extremely annoying to limit default arguments
>> to being literal constants,
> This is a possible solution, beside re-executing the default argument
> expression on each call.

That's no solution at all, because default arguments should not be 
limited to literal constants. That's unacceptable in my opinion.

>> unless you invent some kind of scheme for declaring that a type is safe
>> to use as a default argument.
> Well, it seems functional-style programming may become more common in
> the future, and seeing languages like Scala, etc, maybe it can be useful
> to add to Python some way to define immutable classes (in an explicit
> way). Maybe subclasses of Immutable?

You're still assuming that the behaviour is a bug. It's not, it's a 

>> Even if you could change the behaviour of default arguments we would
>> still get equivalent regular questions from the people who initialise
>> class attributes with lists or dictionaries.
> I have seen professional programmers too use class attributes instead of
> instance ones...

That's only a mistake if you don't mean to use class attributes instead 
of instance attributes.


More information about the Python-list mailing list