Convert Variable Name to String?

前端 未结 16 1620
生来不讨喜
生来不讨喜 2020-11-28 04:33

I would like to convert a python variable name into the string equivalent as shown. Any ideas how?

var = {}
print ???  # Would like to see \'var\'
something_         


        
16条回答
  •  暖寄归人
    2020-11-28 04:58

    It's not very Pythonesque but I was curious and found this solution. You need to duplicate the globals dictionary since its size will change as soon as you define a new variable.

    def var_to_name(var):
        # noinspection PyTypeChecker
        dict_vars = dict(globals().items())
    
        var_string = None
    
        for name in dict_vars.keys():
            if dict_vars[name] is var:
                var_string = name
                break
    
        return var_string
    
    
    if __name__ == "__main__":
        test = 3
        print(f"test = {test}")
        print(f"variable name: {var_to_name(test)}")
    

    which returns:

    test = 3
    variable name: test
    

提交回复
热议问题