Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the list of references to an object in Python

All:

a = 1
b = a
c = b

Now I want to get a list of object 1 tagged, which is [a, b, c]. How could I do this?

BTW, how to call variable "a" here officially? I know so far it is a "object tag" for the object, but I have no idea what is the term of it.

Thanks!

why do I need this:

a = b = c = 1 
print a, b, c 
1 1 1
a = 2
print a, b, c 
2 1 1

in other language such as C, a,b,c should be 2 if I re-assign a = 2, but in python, there's no such thing like reference, so the only way to change all the value of a b c is a = b = c = 2 so far as I know, that is why purposed to get all reference of an object.

like image 473
user478514 Avatar asked Dec 03 '10 02:12

user478514


People also ask

Does Python have object references?

A Python program accesses data values through references. A reference is a name that refers to the specific location in memory of a value (object). References take the form of variables, attributes, and items.

Does Python pass list by reference?

Python passes arguments neither by reference nor by value, but by assignment.


4 Answers

As you can see, it's impossible to find them all.

>>> sys.getrefcount(1)
791
>>> sys.getrefcount(2)
267
>>> sys.getrefcount(3)
98
like image 88
Kabie Avatar answered Sep 17 '22 16:09

Kabie


I'd like to clarify some misinformation here. This doesn't really have anything to do with the fact that "ints are immutable". When you write a = 2 you are assigning a and a alone to something different -- it has no effect on b and c.

If you were to modify a property of a however, then it would effect b and c. Hopefully this example better illustrates what I'm talking about:

>>> a = b = c = [1]  # assign everyone to the same object
>>> a, b, c
([1], [1], [1])
>>> a[0] = 2         # modify a member of a
>>> a, b, c
([2], [2], [2])      # everyone gets updated because they all refer to the same object
>>> a = [3]          # assign a to a new object
>>> a, b, c
([3], [2], [2])      # b and c are not affected
like image 32
mpen Avatar answered Sep 17 '22 16:09

mpen


I think you might be interested in objgraph. It allows you to traverse the object graph in memory, or dump a PNG of your object graph. It's useful for debugging memory leaks.

See this page: http://mg.pov.lt/objgraph/

like image 42
Erik Kaplun Avatar answered Sep 19 '22 16:09

Erik Kaplun


It is not possible to find all references to a given object in Python. It is not even possible to find all objects or all references in Python. (The CPython function gc.get_objects does this, but it is not portable across Python implementations.)

You can use dir() or locals() to find all variables that exist at some scope in the program. But if objects have been defined in other places, you could miss them with this method.

like image 42
Heatsink Avatar answered Sep 20 '22 16:09

Heatsink