Getting the name of a variable as a string

前端 未结 23 2662
旧时难觅i
旧时难觅i 2020-11-22 00:19

This thread discusses how to get the name of a function as a string in Python: How to get a function name as a string?

How can I do the same for a variable? As oppose

23条回答
  •  名媛妹妹
    2020-11-22 00:57

    I have a method, and while not the most efficient...it works! (and it doesn't involve any fancy modules).

    Basically it compares your Variable's ID to globals() Variables' IDs, then returns the match's name.

    def getVariableName(variable, globalVariables=globals().copy()):
        """ Get Variable Name as String by comparing its ID to globals() Variables' IDs
    
            args:
                variable(var): Variable to find name for (Obviously this variable has to exist)
    
            kwargs:
                globalVariables(dict): Copy of the globals() dict (Adding to Kwargs allows this function to work properly when imported from another .py)
        """
        for globalVariable in globalVariables:
            if id(variable) == id(globalVariables[globalVariable]): # If our Variable's ID matches this Global Variable's ID...
                return globalVariable # Return its name from the Globals() dict
    

提交回复
热议问题