I wanted it for debugging, so I made it myself.
In python, there is a built-in variable in the namespace, so search for it.
(Use namespace variables locals ()
and globals ()
.)
The reference of the variable is not unique, but the reference destination of the variable is unique (... isn't it?).
(Use the identifier function ʻid ()
`.)
def getVarsNames( _vars, symboltable ) :
"""
This is wrapper of getVarName() for a list references.
"""
return [ getVarName( var, symboltable ) for var in _vars ]
def getVarName( var, symboltable, error=None ) :
"""
Return a var's name as a string.\nThis funciton require a symboltable(returned value of globals() or locals()) in the name space where you search the var's name.\nIf you set error='exception', this raise a ValueError when the searching failed.
"""
for k,v in symboltable.iteritems() :
if id(v) == id(var) :
return k
else :
if error == "exception" :
raise ValueError("Undefined function is mixed in subspace?")
else:
return error
if __name__ == "__main__":
a = 4
b = "ahoo"
print getVarsNames([a,b,"c"],locals())
This is the return value.
['a', 'b', None]
what about? What happens if you call it from a function that is nested repeatedly?
Postscript: Feel free to send exceptions.
Recommended Posts