Getting the name of a variable as a string

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

    Maybe this could be useful:

    def Retriever(bar):
        return (list(globals().keys()))[list(map(lambda x: id(x), list(globals().values()))).index(id(bar))]
    

    The function goes through the list of IDs of values from the global scope (the namespace could be edited), finds the index of the wanted/required var or function based on its ID, and then returns the name from the list of global names based on the acquired index.

提交回复
热议问题