Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Get all variable names for an object in global scope [duplicate]

Tags:

python

I'll explain with 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']

The requirement: return names of all variables pointing to the same reference. Is this at all possible with python?

I'm thinking something along the lines of iterating over globals() and locals() and equating ids. Is there anything better?

like image 383
cs95 Avatar asked Oct 29 '22 03:10

cs95


1 Answers

For global variables you can do:

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

If you want local names too, you can use the inspect module:

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']
like image 179
jdehesa Avatar answered Nov 15 '22 06:11

jdehesa