Help understanding the decisions *behind* python?

Beni Cherniavsky beni.cherniavsky at gmail.com
Fri Jul 24 07:13:09 EDT 2009


On Jul 22, 9:36 am, Hendrik van Rooyen <hend... at microcorp.co.za>
wrote:
> On Tuesday 21 July 2009 15:49:59 Inky 788 wrote:
>
> > My guess is that it was probably for optimization reasons long ago.
> > I've never heard a *good* reason why Python needs both.
>
> The good reason is the immutability, which lets you use
> a tuple as a dict key.  
>
On Jul 22, 9:36 am, Hendrik van Rooyen <hend... at microcorp.co.za>
wrote:
> On Tuesday 21 July 2009 15:49:59 Inky 788 wrote:
>
> > My guess is that it was probably for optimization reasons long ago.
> > I've never heard a *good* reason why Python needs both.
>
> The good reason is the immutability, which lets you use
> a tuple as a dict key.
>
The *technical* reason is immutability for dict keys.
Dict could allow mutable objects as keys by comparing *by value*,
making a copy on insertion and hashing the current value on lookup.
Prior art: the 2.3 sets module allows mutable Sets as elements in
Sets, by making ImmutableSet copies on insertion, and hashing Sets as
if they are temporarily immutable on lookup.

This inspired PEP 351 and ambitious proposals to expand the approach
to all Python with a copy-on-write scheme.  But these ideas were
rejected, and the 2.4 builtin sets only allow frozenset elements.
Half the reason is technical: copy-on-write and harder than it sounds,
and without it you pay a performance price.

But the deeper reason is style: immutable types are convenient!
The allow a pure-functional style of code, which can be simpler.
Of course, sometimes an imperative style is simpler.  Depends on the
problem.

My rule of thumb:
- Use mutable lists when you are likely to modify individual elements.
- Use immutable tuples when you are likely to replace the whole thing.

(In practice, this boils down to similar usage to the "official" rule
of thumb that lists are for homogenous data, and tuples for
heterogenous records.)



More information about the Python-list mailing list