Getting references to obect instances into a list
Jeremy Sanders
jeremy+complangpython at jeremysanders.net
Wed Aug 27 11:43:27 EDT 2008
parent.eric.3 at gmail.com wrote:
> I will read the article you told me to but first, please, have a look
> at this snippet:
>
>>>> m = [2,3,4]
>>>> p = ['a','b','c']
>>>> q = [m,p]
>>>> q
> [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']]
>>>> del p
>>>> q
> [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']]
>>>>
>
>
> How come q is not updated after I deleted p?
q still holds a reference to p. Maybe you are after weak references. Have a
look at the documentation for the weakref module in the standard library.
Unfortunately you cannot store weak references to lists directly:
In [5]: class foo(object):
...: def __init__(self, lst):
...: self.lst = lst
In [6]: m = foo([2,3,4])
In [7]: p = foo(['a','b','c'])
In [8]: import weakref
In [20]: q = [weakref.proxy(m), weakref.proxy(p)]
In [23]: q[0].lst, q[1].lst
Out[23]: ([2, 3, 4], ['a', 'b', 'c'])
In [24]: del p
In [27]: q[1].lst
gives a reference error
--
Jeremy Sanders
http://www.jeremysanders.net/
More information about the Python-list
mailing list