In Python, is there a way for an instance of an object to see the variable name it\'s assigned to? Take the following for example:
class MyObject(object):
I was independently working on this and have the following. It's not as comprehensive as driax's answer, but efficiently covers the case described and doesn't rely on searching for the object's id in global variables or parsing source code...
import sys
import dis
class MyObject:
def __init__(self):
# uses bytecode magic to find the name of the assigned variable
f = sys._getframe(1) # get stack frame of caller (depth=1)
# next op should be STORE_NAME (current op calls the constructor)
opname = dis.opname[f.f_code.co_code[f.f_lasti+2]]
if opname == 'STORE_NAME': # not all objects will be assigned a name
# STORE_NAME argument is the name index
namei = f.f_code.co_code[f.f_lasti+3]
self.name = f.f_code.co_names[namei]
else:
self.name = None
x = MyObject()
x.name == 'x'