Getting the name of a variable as a string

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

    just another way to do this based on the content of input variable:

    (it returns the name of the first variable that matches to the input variable, otherwise None. One can modify it to get all variable names which are having the same content as input variable)

    def retrieve_name(x, Vars=vars()):
        for k in Vars:
            if type(x) == type(Vars[k]):
                if x is Vars[k]:
                    return k
        return None
    

提交回复
热议问题