[Python-ideas] fixing mutable default argument values

Chris Rebert cvrebert at gmail.com
Wed Jan 17 03:49:14 CET 2007

Calvin Spealman wrote:
> There are a few problems here. Deep copy of the originally created
> default argument can be expensive
For immutables, yes, it would make an unnecessary copy, though it seems 
less likely to have complex immutable objects than complex mutable 
objects as defaults.

> and would not work in any useful way
> with non-literals as defaults, such as function calls or subscript
> lookups or even simple attributes.
Good point, I hadn't considered that.

> If any solution is possible, it would require a way to differentiate
> between mutable and immutable objects, and evaluate the immutables for
> every call.
That doesn't seem to consider the other cases you just mentioned, though 
I see merit in your idea. How about there be some way to specify that a 
default argument value be re-evaluated at every call it's required for, 
while all other arguments have existing semantics?

Hypothetical syntax:

def foo(a, b=4, c=<Bar([q, w, e], 7)>):
     #b's default value is evaluated exactly once, at definition-time
     #c's default value is evaluated every time foo() is called and no 
value for c is given

Where the <>s indicate these special semantics.

> Any solution would be an unjust addition of expense to defaults.
That sounds a bit like premature optimization to me.

- Chris Rebert

More information about the Python-ideas mailing list