Question about references/copies
Alex Martelli
aleaxit at yahoo.com
Sat Aug 28 07:18:34 EDT 2004
Terry Reedy <tjreedy at udel.edu> wrote:
> "Henning Kage" <c0dec at gmx.de> wrote in message
> news:pan.2004.08.28.07.52.35.422774 at gmx.de...
> > I'm using Python only for some months now and I'm wondering, whether such
> > assignments as above are creating bitwise copies of an object or just
> > recieve a reference. That means I wanted to know, wheter Python in
> > general
> > differs between references and copies:
>
> Better to think of Python this way: it has objects and bindings of objects
> to one or more targets (names and slots of composite objects). Binding
> statements (target = expression) always and only assign targets to objects.
Yes, the binding per se never does anything more, if it is to a bare
name (if it's to an indexing, a slicing, or an attribute reference aka a
dotted name, things can become more interesting sometimes). And
normally the expression itself makes no copies unless copies are
specifically requested in it. Slicing though is the interesting part.
Slicing always creates a new object (except that whole-object slicing of
an immutable sliceable need not). But the interesting issue is with the
TARGETS, the SLOTS, inside that new object. Are they the SAME slots as
in the object being sliced? If said object is a list or instance of
array.array -- no, the slots are new and separate ones.
E.g., consider:
>>> z = []
>>> a = [ z, z, 23 ]
>>> sys.getrefcount(z)
4
>>> b = a[:]
>>> sys.getrefcount(z)
6
Here, slicing does create three new slots, two of which are additional
references to the same list object z refers to. However:
>>> z = []
>>> a = Numeric.zeros((3,), 'O')
>>> a[0]=a[1]=z
>>> sys.getrefcount(z)
4
>>> b = a[:]
>>> sys.getrefcount(z)
4
Here, slicing "shares" the SAME slots that 'a' already had, so there is
no change in the reference count of the list object z refers to.
Alex
More information about the Python-list
mailing list