Search code examples
pythonvariablesreference

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.


Solution

  • What you're asking isn't very practical and isn't possible. Here's one crazy way of doing it:

    >>> a = 1
    >>> b = a
    >>> c = b
    >>> locals()
    {'a': 1, 'c': 1, 'b': 1, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
    >>> [key for key, value in locals().items() if value == 1]
    ['a', 'c', 'b']
    >>> globals()
    {'a': 1, 'c': 1, 'b': 1, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
    >>> [key for key, value in globals().items() if value == 1]
    ['a', 'c', 'b']