Getting the name of a variable as a string

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

    I try to get name from inspect locals, but it cann't process var likes a[1], b.val. After it, I got a new idea --- get var name from the code, and I try it succ! code like below:

    #direct get from called function code
    def retrieve_name_ex(var):
        stacks = inspect.stack()
        try:
            func = stacks[0].function
            code = stacks[1].code_context[0]
            s = code.index(func)
            s = code.index("(", s + len(func)) + 1
            e = code.index(")", s)
            return code[s:e].strip()
        except:
            return ""
    

提交回复
热议问题