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):
pass
x = MyObject()
Is it possible for MyObject to see it’s been assigned to a variable name x at any point? Like in it’s __init__ method?
No. Objects and names live in separate dimensions. One object can have many names during its lifetime, and it’s impossible to determine which one might be the one you want. Even in here:
two names denote the same object (
selfwhen__init__runs,xin global scope).