How to write a function to return the variable name?

后端 未结 6 1377
自闭症患者
自闭症患者 2020-12-04 03:59

I want a function that can return the variable/object name as str like this :

def get_variable_name (input_variable):
    ## some codes

>>get_variable         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 04:42

    Perhaps you can use traceback.extract_stack() to get the call stack, then extract the variable name(s) from the entry?

    def getVarName(a):
        stack = extract_stack()
        print(stack.pop(-2)[3])
    
    bob = 5
    getVarName(bob);
    

    Output:

    getVarName(bob)
    

提交回复
热议问题