Getting the name of a variable as a string

前端 未结 23 2705
旧时难觅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:42

    Many of the answers return just one variable name. But that won't work well if more than one variable have the same value. Here's a variation of Amr Sharaki's answer which returns multiple results if more variables have the same value.

    def getVariableNames(variable):
        results = []
        globalVariables=globals().copy()
        for globalVariable in globalVariables:
            if id(variable) == id(globalVariables[globalVariable]):
                results.append(globalVariable)
        return results
    
    a = 1
    b = 1
    getVariableNames(a)
    # ['a', 'b']
    

提交回复
热议问题