Search code examples
pythonpython-3.xclassglobal-variables

How to get variable name from another module in python


When I execute test.py

tests.py

class A():
    def prints(self,*f):
        for j in f:
            for i in globals():
                if globals()[i]==j:
                    print(f'{i}={j}')
            

s=3;id=2 #it will discard when executing main.py
a=A()
a.prints(s,id)

I get the output:

s=3 id=2

But if I import from another program

main.py

from tests import A
if __name__ =='__main__':
    
    id=3
    s=1
    a=A()
    a.prints(s,id)

I get nothing.

How do I get the same output as the former one?


Solution

  • Your prints function does not scale. what happens if there are a multiple variables with the same value you supply to your function?

    This is what you want

    In [1]: import sys
    
    In [2]: class A():
       ...:     def prints(self,*f):                                                                        ...:         # get the caller's frame with sys._getframe
       ...:         frame = sys._getframe(1)
       ...:         # get all variables in the caller's namespace
       ...:         all_vars = frame.f_locals
       ...:         for j in f:
       ...:             for i in all_vars:
       ...:                 if all_vars[i]==j:
       ...:                     print(f'{i}={j}')
       ...:
    
    In [3]: a = A()
    
    In [4]: a.prints(a)
    a=<__main__.A object at 0x763c377790>