[Tutor] no. of references

Steven D'Aprano steve at pearwood.info
Tue Jun 8 12:07:28 CEST 2010


On Tue, 8 Jun 2010 04:08:15 pm Payal wrote:
> Hi,
> If I have a list (or a dict), is there any way of knowing how many
> other variables are referencing the same object?

Sort of. The question is simple, but the answer isn't. It depends what 
you mean by "variables", and it requires a good understanding of 
Python's programming model.

Python doesn't have "variables" like C or Pascal, it has names and 
objects. Objects can be bound to no names at all:

len([1,2,4])

or to a single name:

x = [1,2,4]
len(x)

or to multiple names:

x = y = z = [1,2,4]
w = y
len(w)


Objects can also be referenced by other objects, which in turn could 
have zero, one or more names. Consider this example:

>>> a = [1,2,4]
>>> b = a
>>> c = {None: ('xyz', b)}
>>> class K:
...     pass 
...
>>> d = K()
>>> d.attr = [c]


Given your question, how many "variables" refer to the list [1,2,4]?, 
what answer would you expect? Depending on how I count them, I get 
either 4, 5 or 6:

4:
"variables" (names) a, b, c and d

5:
the dict globals() has two references to the list, using keys 'a' 
and 'b';
the tuple ('xyz', b);
the dict with key None and value the above tuple;
the list [c];
the instance d has a dict __dict__ with key 'attr'

6:
same as five, but counting globals() twice


Interestingly, Python has a standard tool for tracking referrers, the gc 
(garbage collector) module, and it disagrees with all of those counts:

>>> import gc
>>> len(gc.get_referrers(a))
2
>>> print gc.get_referrers(a)
[('xyz', [1, 2, 4]), {'a': [1, 2, 4], 'c': {None: ('xyz', [1, 2, 
4])}, 'b': [1, 2, 4], 'd': <__main__.C instance at 0xb7f6008c>, 'gc': 
<module 'gc' (built-in)>, '__builtins__': <module '__builtin__' 
(built-in)>, 'C': <class __main__.C at 
0xb7d0602c>, '__name__': '__main__', '__doc__': None}]

So gc says two objects *directly* refer to the list: the tuple, and 
globals(). But of course there are multiple *indirect* references to 
the list as well. So the answer you get depends on the way you ask it.


-- 
Steven D'Aprano


More information about the Tutor mailing list