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):
Here is a simple function to achieve what you want, assuming you wish to retrieve the name of the variable where the instance is assigned from a method call :
import inspect
def get_instance_var_name(method_frame, instance):
parent_frame = method_frame.f_back
matches = {k: v for k,v in parent_frame.f_globals.items() if v is instance}
assert len(matches) < 2
return list(matches.keys())[0] if matches else None
Here is an usage example :
class Bar:
def foo(self):
print(get_instance_var_name(inspect.currentframe(), self))
bar = Bar()
bar.foo() # prints 'bar'
def nested():
bar.foo()
nested() # prints 'bar'
Bar().foo() # prints None