Convert Variable Name to String?

前端 未结 16 1594
生来不讨喜
生来不讨喜 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:56

    Here is a succinct variation that lets you specify any directory. The issue with using directories to find anything is that multiple variables can have the same value. So this code returns a list of possible variables.

    def varname( var, dir=locals()):
      return [ key for key, val in dir.items() if id( val) == id( var)]
    

提交回复
热议问题