I have a following code:
class A: def m(self): print(...) # 'my_var' should be printed my_var = A() my_var.m() What code should I type inside of m to output the name of the created variable? I need a solution for Python 3.
Objects don't know what namespace variables they happen to be bound to at any given time. Such variables have a forward reference to the object, but the object does not maintain a back reference to the potentially-many variables. Imported modules are listed in sys.modules and you can scan those for your object. This would catch module-level variables but not any container, class, class instance or local function namespace that happens to hold the variable also.
test1.py - Implements class that scans for itself in known modules
import sys class A: def m(self): for name, module in sys.modules.items(): try: for varname, obj in module.__dict__.items(): if obj is self: print('{}.{}'.format(name, varname)) except AttributeError: pass a = A() test2.py - tests the code
import test1 my_a = test1.a my_a.m() running the code
$ python3 test2.py __main__.my_a test1.a sys.modules or inspect. I understand all problems related to my question and the philosophy that it shouldn't be possible.
a= b= c= A()ora= A(); def f():b= aorA().m()?A().m()orx = [A()]; x[0].m().