简体   繁体   English

在运行时在 Python3 中获取局部变量的名称

[英]Getting name of local variable at runtime in Python3

I want to get variable name in function so here:我想在 function 中获取变量名,所以在这里:

def foo(bar):
    print(getLocalVaribalename(bar))

I want 'bar' to be printed.我想要打印“bar”。 so I found the code for global variables所以我找到了全局变量的代码

def varName(variable,globalOrLocal=globals()):
    for name in list(globalOrLocal.keys()):
        expression = f'id({name})'
        if id(variable) == eval(expression):
            return name

and I sent varName(bar,locals()) to it like this我像这样向它发送了varName(bar,locals())

def foo(bar):
    print(varName(bar,locals()))

but gives NameError: name 'bar' is not defined error.但给出NameError: name 'bar' is not defined错误。

I also found Getting name of local variable at runtime in Python which is for python 2 but the syntax is completely different.我还在 Python 中找到了 Getting name of local variable at runtime python 2 但语法完全不同。 note that the main goal is to get the name of local variable and not necessarily with this code(varName function which is defined few lines earlier).请注意,主要目标是获取局部变量的名称,不一定使用此代码(varName function,它在前面几行中定义)。

import sys
def getlocalnamesforobj(obj):
    frame = sys._getframe(1)
    return [key for key, value in frame.f_locals.items() if value is obj]

This introspects the local variables from the calling function. One obvious problem is, of course, there might be more than one name pointing to the same object, so the function returns a list of names.这会检查来自调用 function 的局部变量。一个明显的问题是,当然,可能有多个名称指向同一个 object,因此 function 返回一个名称列表。

As put in the comments, however, I can't perceive how this can be of any use in any real code.然而,正如评论中所说,我无法理解这在任何实际代码中有何用处。

As a rule of thumb, if you need variable names as data (strings), you probably should be using a dictionary to store your data instead.根据经验,如果您需要变量名称作为数据(字符串),您可能应该使用字典来存储数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM