3

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.

5
  • 1
    I don't imagine that this is possible, or at least it shouldn't be possible. A function should not need to know that. Why would you possibly need this? Commented Apr 20, 2017 at 15:08
  • Objects don't know which namespaces they happen to be bound to at any given time. You could scan loaded modules for the object, which would catch some. But it wouldn't catch any active function namespaces or container objects holding the object. Is that sufficient? Commented Apr 20, 2017 at 15:13
  • What output would you expect if I do a= b= c= A() or a= A(); def f():b= a or A().m()? Commented Apr 20, 2017 at 15:25
  • If you're feeling crazy you could inspect the stack for variables containing the same reference as self, but that will fail if there are no locals containing self, like if it was never stored in a variable, e.g. A().m() or x = [A()]; x[0].m(). Commented Apr 20, 2017 at 15:32
  • Let's be real here: there is no good reason to ever do what OP is trying to do. I hope this question is asked out of curiousity only. Commented Apr 20, 2017 at 15:36

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it worked. I expected a solution like this using sys.modules or inspect. I understand all problems related to my question and the philosophy that it shouldn't be possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.