I need to print variable names, so I did:
def get_variable_name(x):
local_matches = [k for k, v in locals().items() if v is x]
global_matches = [k for k, v in globals().items() if v is x]
print(local_matches, global_matches)
return global_matches[0]
a = 5
print(get_variable_name(a))
# output
# (['x'], ['a'])
# a
That's now perfect, but now I need to use this get_variable_name
function in many places in my project. So I moved this function to utils.py
, and we can now import it and use it like:
from scripts.utils import get_variable_name
a = 5
print(get_variable_name(a))
# output
# (['x'],[])
# ! can't access index 0 exception
# ! since the list is empty
Clearly, in the former, a is found in the global var stack and in the latter it's not, since when it's inside of utils.py
executing this functions, globals()
does not contain a
, since it is not declared in the global scope (of the file).
So we got locals().items()
to give local vars, and globals().items()
for global vars, How do I access inter-file scope variable stack?
UPDATE:
In another SO question, mentioned in the comments, they are dealing with variables defined in the global scope in file1
and this will not be available in file2
because, file1
imports only modules of file2
.
But here, I am sending these variables to file2
, and obviously, values of which itfile2
has access to, but how do I access the names of the arguments passed? (And I don't see a security or dependency flaw associated with this, as it already has access to the variable, I just want their names)