Unexpected result for list operator "+="

Fredrik Lundh fredrik at effbot.org
Fri Jan 5 06:14:52 EST 2001


Alex Martelli wrote:
> > There's no distinction between mutable and immutable objects
> > in Python itself.  An object is immutable only if it doesn't have
> > any methods that allow you to change its content.  Neither you
> > nor Python can do an "ismutable(x)" test.
>
> Isn't there a _convention_ about 'immutability' being the
> prerequisite for usage as a dictionary-key?  It is, of course,
> defined in terms of 'hashability':
>
> >>> d={}
> >>> d[(1,2)]=3
> >>> d[[4,5]]=6
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: unhashable type
> >>>
>
> not in terms of 'mutability'... but it's _meant_ to have
> something to do with mutability, at least in as much as
> the latter affects comparisons, no?

The "at least in as much as" is the important part here; an
object can be mutable (change contents without changing
its identity) but still be used everywhere a "truly immutable"
object can be used -- just make sure that the hash value
doesn't change, and follow the "objects that compare equal
must have the same hash value" rule.

(e.g. objects using internal caches, usage counters, etc)

> I wonder if this convention is clearly documented some-
> where...

imho, most writers tend to mess things up when talking about
the object model.  I've seen several Python introductions that
attempt to hide the details, and then use exercises to show
that it might not work as we just described it...

(that's why I'm working on "the eff-bot guide to Python" in my
copious spare time ;-)

Cheers /F





More information about the Python-list mailing list