如何在运行时在python中检索变量的名称? [英] How to retrieve a variable's name in python at runtime?

查看:60
本文介绍了如何在运行时在python中检索变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在运行时知道变量的名称(从代码中)?或者在编译过程中忘记了变量的名称(字节码与否)?

例如:

<前>>>> 变量 = 15>>> 打印变量~~名称~~()'变'

注意:我说的是纯数据类型变量(intstrlist 等.)

解决方案

这里有一个基本的(可能很奇怪的)函数,它显示了它的参数的名字......这个想法是分析代码并搜索对函数的调用(在 init 方法中添加它可以帮助找到实例名称,尽管代码分析更复杂)

def display(var):进口检验,重新callframe = inspect.currentframe().f_backcntext = "".join(inspect.getframeinfo(callingframe, 5)[3]) #获取5行m = re.search("display\s+\(\s+(\w+)\s+\)", cntext, re.MULTILINE)打印 m.group(1), type(var), var

请注意:从调用代码中获取多行有助于防止调用被拆分,如下例所示:

显示(我的_var)

但会产生意想不到的结果:

display(first_var)显示(second_var)

如果您无法控制项目的格式,您仍然可以改进代码以检测和管理不同的情况...

总的来说,我猜静态代码分析可以产生更可靠的结果,但我现在懒得检查

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.:

>>>  vari = 15
>>>  print vari.~~name~~()
'vari'

Note: I'm talking about plain data-type variables (int, str, list etc.)

解决方案

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

这篇关于如何在运行时在python中检索变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆