How to retrieve a variable's name in python at runtime?

后端 未结 8 1493
悲哀的现实
悲哀的现实 2020-11-28 13:33

Is there a way to know, during run-time, a variable\'s name (from the code)? Or do variable\'s names forgotten during compilation (byte-code or not)?

e.g.:



        
8条回答
  •  忘掉有多难
    2020-11-28 13:51

    here a basic (maybe weird) function that shows the name of its argument... the idea is to analyze code and search for the calls to the function (added in the init method it could help to find the instance name, although with a more complex code analysis)

    def display(var):
        import inspect, re
        callingframe = inspect.currentframe().f_back
        cntext = "".join(inspect.getframeinfo(callingframe, 5)[3]) #gets 5 lines
        m = re.search("display\s+\(\s+(\w+)\s+\)", cntext, re.MULTILINE)
        print m.group(1), type(var), var
    

    please note: getting multiple lines from the calling code helps in case the call was split as in the below example:

    display(
            my_var
           )
    

    but will produce unexpected result on this:

    display(first_var)
    display(second_var)
    

    If you don't have control on the format of your project you can still improve the code to detect and manage different situations...

    Overall I guess a static code analysis could produce a more reliable result, but I'm too lazy to check it now

提交回复
热议问题