[Tutor] lists, name semantics

Cameron Simpson cs at zip.com.au
Sun Apr 19 07:09:51 CEST 2015


On 18Apr2015 23:26, boB Stepp <robertvstepp at gmail.com> wrote:
>On Sat, Apr 18, 2015 at 11:08 PM, Cameron Simpson <cs at zip.com.au> wrote:
>> Sometimes you want a "deep" copy, where "b" would have got a copy of the
>> iriginal x-y list. See the "copy" module's "deepcopy" function, which
>> supplies this for when it is needed:
>>
>>  https://docs.python.org/3/library/copy.html#copy.deepcopy
>
>In this reference, part of it states:
>
>"Two problems often exist with deep copy operations that don’t exist
>with shallow copy operations:
>
>Recursive objects (compound objects that, directly or indirectly,
>contain a reference to themselves) may cause a recursive loop.
>Because deep copy copies everything it may copy too much, e.g.,
>administrative data structures that should be shared even between
>copies."
>
>If I am understanding things correctly, should not that last sentence
>read instead:
>
>"...structures that should *not* be shared even between copies." ???

No, the text is correct.

Suppose you have a graph of objects where some single object A is referenced in 
mulitple places:

      /--> O1 ----v
  G <              A
      \--> O2 ----^

If I make a deepcopy of "G" I want this:

          /--> O1copy ----v
  Gcopy <                  Acopy
          \--> O2copy ----^

i.e. a _single_ copy "Acopy" of "A", again referenced from 2 places in the 
copied graph.

Without deepcopy()'s object tracking you would get something like this:

          /--> O1copy ----> Acopy1
  Gcopy <
          \--> O2copy ----> Acopy2

i.e. two distinct copies of "A". Changes to "Acopy1" would not affect "Acopy2".

Cheers,
Cameron Simpson <cs at zip.com.au>

They said it couldn't be done/they said nobody could do it/
But he tried the thing that couldn't be done!/He tried - and he couldn't do it.


More information about the Tutor mailing list