Retrieving the list of references to an object in Python

后端 未结 7 1216
栀梦
栀梦 2020-12-04 01:29

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?

相关标签:
7条回答
  • 2020-12-04 02:04

    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']
    
    0 讨论(0)
  • 2020-12-04 02:08

    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.

    0 讨论(0)
  • 2020-12-04 02:12

    First of all in C, "=" is a value assignment and does not create a reference. More specifically when you write a=b=1 what happens is this.

    (1) b=1 gets evaluated, assigns 1 to b and then returns 1, so the expression becomes a=1

    (2) a=1 gets evaluated, assigns 1 to b and then returns 1 which is not used anywhere.

    Then a=1 changes only a as expected.

    In python things are a bit more complicated as every variable is a reference, but it treats numbers differently because they are immutable. In short when you write a=1 and b=1, then a is b returns True. But changing one will not change the other.

    This however does not happen with objects, with them a reference works as expected. So if you want to do what you describe maybe you should define a new object that holds the value you want and assign this to a variable.

    0 讨论(0)
  • 2020-12-04 02:17

    Look at pyjack. Its replace_all_refs function seems to work pretty well to replace all references to an object. Note: Doesn't work well with string objects.

    0 讨论(0)
  • 2020-12-04 02:26

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

    >>> sys.getrefcount(1)
    791
    >>> sys.getrefcount(2)
    267
    >>> sys.getrefcount(3)
    98
    
    0 讨论(0)
  • 2020-12-04 02:27

    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/

    0 讨论(0)
提交回复
热议问题