How to write a function to return the variable name?

后端 未结 6 1375
自闭症患者
自闭症患者 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:48

    def getvariablename(vara):
        for k in globals():
            if globals()[k] == vara:
                      return k
         return str(vara)
    

    may work in some instance ...but very subject to breakage... and I would basically never use it in any kind of production code...

    basically I cant think of any good reason to do this ... and about a million not to

提交回复
热议问题