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):
Yes, it is possible*. However, the problem is more difficult than it seems upon first glance:
Regardless, knowing how to find the names of an object can sometimes be useful for debugging purposes - and here is how to do it:
import gc, inspect
def find_names(obj):
frame = inspect.currentframe()
for frame in iter(lambda: frame.f_back, None):
frame.f_locals
obj_names = []
for referrer in gc.get_referrers(obj):
if isinstance(referrer, dict):
for k, v in referrer.items():
if v is obj:
obj_names.append(k)
return obj_names
If you're ever tempted to base logic around the names of your variables, pause for a moment and consider if redesign/refactor of code could solve the problem. The need to recover an object's name from the object itself usually means that underlying data structures in your program need a rethink.
* at least in Cpython