Style question - defining immutable class data members
R. David Murray
rdmurray at bitdance.com
Sun Mar 15 17:42:26 EDT 2009
M R A Barnett <pcw at mrabarnett.plus.com> wrote:
> Aaron Brady wrote:
> [snip]
> > However, in my (opined) interpretation, 'list.append(...) is an in-
> > place operation' is a factual error. In-place operations -also-
> > rebind their 'argument' (FLOBW for lack of better words). 'append' is
> > a by-side-effect operation. However colloquially it's mostly
> > accurate.
> >
> [snip]
> All the augmented assignments rebind, even for objects which support
> in-place operations. For example:
>
> my_list = []
> my_list += [0]
>
> rebinds, but the equivalent:
>
> my_list = []
> my_list.extend([0])
>
> doesn't.
Lest someone be mislead by this discussion, how about an example:
>>> a = b = []
>>> a.extend([1])
>>> a
[1]
>>> b
[1]
>>> a += [3]
>>> a
[1, 3]
>>> b
[1, 3]
>>> a = a + [5]
>>> a
[1, 3, 5]
>>> b
[1, 3]
It is technically correct that '+=' bebinds 'a', but what it
rebinds it to is the same object that was just mutated. Unlike
the '+' case where 'a' is bound to a newly created list object.
Personally I think += and kin were a bad idea and should have been
removed in Python 3.0 :) Even though I occasionally use them. (Maybe
I'll stop.)
> Augmented assignments which don't support in-place operations behave
> like normal assignments (binding). For example:
>
> my_int = 0
> my_int += 1
>
> behaves like:
>
> my_int = 0
> my_int = my_int + 1
--
R. David Murray http://www.bitdance.com
More information about the Python-list
mailing list