0

Just for curiosity.. python "variables" are references to objects. Each has a name or "accesser label" so I can refer to them while scripting.

Does each python object keep a list of all "variable names" refering to itself? How would I access it?

# A random object
class A(object):
    pass

# references to instances
a = A()
b = A()
c = a

# I happen to come accross one reference
ref = c

# This is how I find all the ways I can access it
# i.e. all its "accessers" or "variable names"
k, v = None, None # to avoid `RuntimeError: dictionary changed size..`
for k, v in globals().items():
    if v is ref:
        print(k) # prints "a c ref" since `a is c` and `c is ref`

# Is there a way I may get this without looping over all variables? Like a..
ref.__getallreferencenames__() # AttributeError
# Is that information stored and kept up to date somewhere?
iago-lito
  • 3,098
  • 3
  • 29
  • 54

1 Answers1

0

In python varnames and objects are quite different things. First are just keys in hashmap corresponding to some scope (like locals or globals), where second are actual objects in the heap memory. Having that said your question doesnt make to much sense. What you can do though is to get low level references from gc module itself, just call gc.get_referrers(myobj), for example

c.get_referrers(object)
hello world
  • 596
  • 2
  • 12
  • Well, having that said, the question translates to: Given one actual object in the heap, how do I get all varnames leading to it and their corresponding scope? Using `gc.get_referrers(ref)` gives me a lot more than my expected `['a', 'c', 'ref']`. – iago-lito May 04 '17 at 12:13
  • 1
    Yes, because there are much more) And notice that `gc.get_referrers(ref)` gives you a list of objects, not `object -> scope` relations, because scopes are in general available only in runtime of particular code object (bound to frame object). In other words objects and scopes are completely different beasts. On the other hand given a scope as a mapping you can lookup your object in it, but again, this scope should be provided in the first place because it exists only in runtime. – hello world May 04 '17 at 12:36