Yes, it is possible*. However, the problem is more difficult than it seems upon first glance:
- There may be multiple names assigned to the same object.
- There may be no names at all.
- The same name(s) may refer to some other object(s) in a different namespace.
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