Newbie: tuple list confusion.
Alex Martelli
aleaxit at yahoo.com
Mon Sep 13 03:05:04 EDT 2004
More information about the Python-list mailing list
Mon Sep 13 03:05:04 EDT 2004
- Previous message (by thread): Newbie: tuple list confusion.
- Next message (by thread): Newbie: tuple list confusion.
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Elaine Jackson <elainejackson7355 at home.com> wrote: > In addition to what you've found out already, there is another difference > that, to my mind, is of paramount importance; namely, the fact that an > augmented assignment (a+=b) is actually not an assignment at all. An > actual assignment (a=a+b) binds the name "a" to a new object, while a > so-called augmented assignment mutates the object a itself. Ah, careful there: augmented assignment (nothing "so-called" about it;-) mutates the object and THEN assigns ("re-binds" if you want to get technical) the name or other slot holding the object. For example...: >>> L=[] >>> T=(L, L) >>> T[0] += [1] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment If it were true that the += "is actually not an assignment" this behavior and error message would be impossible. It _IS_ an assignment, _augmented_ by the fact that the object in question (if mutable) is also supposed to mutate. Regarding the fact that the mutation takes place before the assignment, this is the kind of behavior details you can check by writing a simple dummy class with the appropriate special method doing a print. For example: >>> class X: ... def __iadd__(self, other): ... print 'iadd running' ... return self ... >>> T = (X(), X()) >>> T[0] += 23 iadd running Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment >>> See? First we see the message "iadd running", so __iadd__ is executing; THEN, the error message about assignment to item not being supported. This is important because the object DOES get mutated even though the assignment fails. If you check the L in the previous fragment, indeed, you'll see it's now [1], not [] any more. Yes, I do agree these subtleties are potentially confusing -- a pity, because Python's foremost strength is mostly to AVOID being confusing. But I don't believe we could have designed +='s behavior to be substantially clearer and yet just as useful as it is today, given all the rest of the details about the way Python works; and I do believe +='s usefulness is sufficient to warrant having it in Python. Alex
- Previous message (by thread): Newbie: tuple list confusion.
- Next message (by thread): Newbie: tuple list confusion.
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list