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 id
s. Is there anything better?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With