surprising behavior of chained initializations

Chris Hoffmann (choffman@dvcorp.com)
Thu, 26 Jan 95 17:09:58 EST

Eric Pettersen writes:
> I believe I understand the behavior of the following script, but I
> don't like it:
>
> >#!/usr/local/bin/python
> >
> >a = b = []
> >
> >a.append("x")
> >b.append("y")
> >
> >print b
>
> The output is "['x', 'y']". I think the naive observer would expect
> "['y']" as the output. Shouldn't the left-hand sides of multiple
> initializations get copies of the right-hand sides, instead of name aliases (or
> whatever)?
>
> --
> Eric Pettersen pett@cgl.ucsf.edu (NeXTmail capable)
>
> These opinions are mine; get your own.

Ah, but ALL assignments in Python are name aliases! A non-naive Python
progammer would certainly find the following even more surprising:

>>> a = [1,2,3]
>>> b1 = b2 = a
>>> b1 is b2
0

I read the second line as essentially saying "b1 and b2 are other
names for the object named a". Why would I expect it to make a copy of
a?

I think the difficulty is that "[]" looks like a "scalar", or an
integer constant, or some bit of syntax-sugar that gets optimized
away, when in fact it truly does create a list object. Given this, it
has to be treated like any other object in the system.

Personally, I don't use chained assignments much so I've never been
bitten by this behavior, though I could easily imagine accidentally
doing just what you did. Has anyone else?

[As an aside, if chained assignments were to make copies, how do you
define "copy" for an arbitrary object? In fact, would a copy of a
list be a deep copy or shallow copy?]

Chris

-- 
Chris Hoffmann				DataViews Corporation
choffman@dvcorp.com			47 Pleasant St. Northampton MA 01060
GCS d H s+: g+ ?p a w v+ C+$ US+ P++(++++) L E+(+++) N++ K W--->-- M+
V- po- Y+ t+ 5+(+++) Jx R G tv b+++ D+ B-() e+++ u++ h---- f r+++ n--- y++++