Unexpected result for list operator "+="

Alex Martelli aleaxit at yahoo.com
Fri Jan 5 04:11:30 EST 2001


"Fredrik Lundh" <fredrik at effbot.org> wrote in message
news:rnf56.3809$Qb7.492757 at newsb.telia.net...
> Greg Jorgensen wrote:
> > The real distinction--that assignment operations on immutable objects
> > create new objects (or bind a reference to a different existing object)
>
> Careful.
>
> Ordinary assignment operations (a = b) bind names in a name-
> space, they never create new objects.

Very good point.  So, it's always the 'or bind a reference'
part.  I.e.: "real" ``assignment'' always does nothing more,
and nothing less, than binding a reference to the object that
is indicated (or built) by the expression to the right of
the '='.  The "create-new or refer-to-existing" happens on
the _right_ of the = sign (just as it may happen in any
other expression); then, the '=' itself never does anything
but the binding.


> Things that may look as assignment operations, but are really
> syntactic sugar for method calls, may do whatever they want:
>
>     a[x] = b # short for __setitem__
>     a.x = b # short for __setattr__
>     a += b # short for __iadd__
>     a.append(b)

An even better point.  Still, there are 'default' behaviors
of these pseudo-assignments when applied to objects that
define nothing special relevant to the 'method call' that
the assignment-like notation stands for.  I realize I'm not
saying this rigorously enough -- but the default behavior
seems to be deserving of full explanation, among other
reasons because it's what defines the 'pattern of least
astonishment', that an author of [e.g.] a __setattr__ method
would be well advised to keep in mind... at least, he or she
will have to document carefully significant deviation from
what the author of client-code would expect (which is sort
of hard if one doesn't precisely know what IS 'expected':-).


> 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?  I wonder if this
convention is clearly documented somewhere...


Alex






More information about the Python-list mailing list