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']
source
share