Python - get all variable names for an object in global scope

I will explain an example:

list_1 = [1, 2, 3]
list_2 = list_3 = list_1 # reference copy

print(magic_method(list_1))
# Should print ['list_1', 'list_2', 'list_3']

set_1 = {'a', 'b'}
print(magic_method(set_1))
# Should print ['set_1']

Requirement: returns the names of all variables pointing to the same link. Is this possible with python?

I think something along the lines of iteration over globals()and locals()and equating ids. Anything better?

+4
source share
2 answers

For global variables, you can:

def magic_method(obj):
    return [name for name, val in globals().items() if val is obj]

If you need local names, you can use the module inspect:

def magic_method(obj):
    import inspect
    frame = inspect.currentframe()
    try:
        names = [name for name, val in frame.f_back.f_locals.items() if val is obj]
        names += [name for name, val in frame.f_back.f_globals.items()
                  if val is obj and name not in names]
        return names
    finally:
        del frame

And then:

list_1 = [1, 2, 3]
list_2 = list_1

def my_fun():
    list_3 = list_1
    list_2 = list_1
    print(magic_method(list_1))

my_fun()
>>> ['list_3', 'list_1', 'list_2']
+2
source

It works:

def magic_method(var):
     names = filter(lambda x: globals()[x] is var, globals().keys())
     return names

isperforms a comparative comparison. Add list(...)to the resulting expression if you are using Python3.

-2
source

Source: https://habr.com/ru/post/1683669/


All Articles