Tuesday, July 10, 2012

deep copy vs shallow copy vs weakref

look at the following example:

import copy
list = [ ['a'] ]
list_copy = copy.copy(list)
list_copy[0].append('b')
print list, list_copy

output is: 

[['a', 'b']] [['a', 'b']]

the lets try:

import copy
list = [ ['a'] ]
list_copy = copy.copy(list)
list_copy.append('b')
print list, list_copy

output is: 

[['a']] [['a'], 'b']


the above shows shallow copy, which share the element, but not the obj of list itself
a deep copy will not share anything as a brand new separate obj.

so what is the weakref used for?

class LeakTest(object):
   def __init__(self):
     print 'Object with id %d born here.' % id(self)
   def __del__(self):
     print 'Object with id %d dead here.' % id(self)
def foo():
   A = LeakTest()
   B = LeakTest()
   A.b = B
   B.a = A
foo()


output is: 

Object with id 71183792 born here.
Object with id 71182608 born here.

the object of A and B are not deleted, why? cus they refer to each other, cause a dead lock that can not delete the objs, that is why we need weakref:

import weakref
class LeakTest(object):
   def __init__(self):
     print 'Object with id %d born here.' % id(self)
   def __del__(self):
     print 'Object with id %d dead here.' % id(self)
def foo():
   A = LeakTest()
   B = LeakTest()
   A.b = weakref. proxy (B)
   B.a = weakref. proxy (A)
foo()


output is: 

Object with id 71180816 born here.
Object with id 71181008 born here.
Object with id 71180816 dead here.
Object with id 71181008 dead here.

No comments:

Post a Comment