Python deepcopy, dictionary value when changing an object

I have a snippet of Python code:

import copy

class Foo(object):
    bar = dict()

    def __init__(self, bar):
        self.bar = bar

    def loop(self):
        backup = copy.deepcopy(self)
        backup.bar[1] = "1"
        for i in range(0, 10):
            print "BACKUP BAR IS: ", backup.bar
            self.bar[1] = "42"
            self.bar = backup.bar

a = Foo({1:"0"})
a.loop()

This prints the BACKUP BAR IS: {1: '1'}first two times, but then starts to print the BACKUP BAR IS: {1: '42'}next eight times. Can someone tell me how and why this happens? Does it create a deepcopynew instance self? How does the value of backupbar change when we change the value of "self", which is "a", in this case?

Edit: some noted that the line self.bar = backup.barforces two dicts to point to each other. But if we do this:

 a = {1:1}
 b = {1:2}
 c = {1:3}
 a = b
 a = c

a b , a, b, c c. a = c = {1:3}, b = {1:2}. , . , backup.bar , self.bar?

+4
3

self.bar = backup.bar , self.bar, backup.bar self.bar. , self.bar backup.bar, . :

In [48]: a = Foo({1: "0"})

In [49]: backup = copy.deepcopy(a)

In [50]: a.bar = backup.bar

In [51]: id(backup.bar)
Out[51]: 140428501511816

In [52]: id(a.bar)  # Same object! Alternatively, `a.bar is backup.bar` -> True
Out[52]: 140428501511816

In [53]: backup.bar[1] = "42"

In [54]: a.bar
Out[54]: {1: '42'}

@alfasin.

, , b. , a . a = c b = c. , a b, c.

, .

a ---> {1: 1}
b ---> {1: 2}
c ---> {1: 3}

a = b:

a --------   # So long, {1: 1}
         |
         v
b ---> {1: 2}
c ---> {1: 3}

a = c, a , c :

a ---------------
                |
                |
b ---> {1: 2}   |
c ---> {1: 3} <-|
+4

:

self.bar[1] = "42"
self.bar = backup.bar

backup.bar, {1:'1'}.

, self.bar = backup.bar, , self.bar, backup.bar, . , ( - ) BACKUP BAR IS: {1: '42'} ( - , , , ).

+2

I believe your problem lies in this line

self.bar = backup.bar

Now you set self.bar to point to backup.bar now, so when you change self.bar you also change backup.bar and vice versa

+1
source

All Articles