Late-binding of function defaults (was Re: What is a function parameter =[] for?)

Steven D'Aprano steve at pearwood.info
Thu Nov 26 20:23:11 EST 2015


On Thu, 26 Nov 2015 07:27 pm, Marko Rauhamaa wrote:

> What I'm saying is that Python does not prevent mutable keys but tries
> to do that with lists and tuples.
> 
> I think Python should stop trying.
> 
> I have wanted to use lists as keys, and there should be no reason to
> allow mutable tuples. It should be enough to say that the behavior of a
> dictionary is undefined if a key should mutate on the fly.

Well, when you design your own language, you can make all the bad design
decisions you like :-)

Seriously, if you think *this* thread about mutable function defaults has
been long, can you imagine the bug reports and arguments if this was
possible in Python?


L = [1, 2]
d = {L: "found it"}

# much later, after L has been modified...

d[ [1, 2] ]
=> raises KeyError



But even worse:


a = [1, 2]
b = [1, 3]
d = {a: "spam", b: "ham"}
a[1] += 1

What will d[ [1, 3] ] return?


-- 
Steven




More information about the Python-list mailing list