如何在Python中打印变量名?

发布于 2024-07-14 02:34:32 字数 602 浏览 8 评论 0原文

假设我有一个名为 choice 的变量,它等于 2。我如何访问该变量的名称? 相当于

In [53]: namestr(choice)
Out[53]: 'choice'

用于制作字典的东西。 有一个很好的方法可以做到这一点,但我只是想念它。

编辑:

这样做的原因是这样的。 我正在运行一些数据分析的东西,我用多个参数调用程序,我想在运行时调整或不调整这些参数。 我从格式为“提示输入值时”的 .config 文件中读取了上次运行中使用的参数。

filename
no_sig_resonance.dat

mass_peak
700

choice
1,2,3

当提示输入值时,将显示先前使用的值,并且空字符串输入将使用先前使用的值。

我的问题出现是因为在编写这些值已被扫描到的字典时。 如果需要参数,我运行 get_param 来访问文件并查找参数。

我想我可以通过读取 .config 文件一次并从中生成字典来避免这个问题。 我最初避免这样做的原因……我已不记得了。 更新我的代码的完美情况!

Say I have a variable named choice it is equal to 2. How would I access the name of the variable? Something equivalent to

In [53]: namestr(choice)
Out[53]: 'choice'

for use in making a dictionary. There's a good way to do this and I'm just missing it.

EDIT:

The reason to do this is thus. I am running some data analysis stuff where I call the program with multiple parameters that I would like to tweak, or not tweak, at runtime. I read in the parameters I used in the last run from a .config file formated as

filename
no_sig_resonance.dat

mass_peak
700

choice
1,2,3

When prompted for values, the previously used is displayed and an empty string input will use the previously used value.

My question comes about because when it comes to writing the dictionary that these values have been scanned into. If a parameter is needed I run get_param which accesses the file and finds the parameter.

I think I will avoid the problem all together by reading the .config file once and producing a dictionary from that. I avoided that originally for... reasons I no longer remember. Perfect situation to update my code!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

情栀口红 2024-07-21 02:34:32

如果你坚持的话,这里有一些可怕的基于检查的解决方案。

import inspect, re

def varname(p):
  for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
    m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
    if m:
      return m.group(1)

if __name__ == '__main__':
  spam = 42
  print varname(spam)

我希望它能激励您重新评估您遇到的问题并寻找另一种方法。

If you insist, here is some horrible inspect-based solution.

import inspect, re

def varname(p):
  for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
    m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
    if m:
      return m.group(1)

if __name__ == '__main__':
  spam = 42
  print varname(spam)

I hope it will inspire you to reevaluate the problem you have and look for another approach.

无尽的现实 2024-07-21 02:34:32

要回答您原来的问题:

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]

示例:

>>> a = 'some var'
>>> namestr(a, globals())
['a']

作为 @ rbright 已经指出无论你做什么,可能都有更好的方法来做到这一点。

To answer your original question:

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]

Example:

>>> a = 'some var'
>>> namestr(a, globals())
['a']

As @rbright already pointed out whatever you do there are probably better ways to do it.

戈亓 2024-07-21 02:34:32

如果你试图这样做,那就意味着你做错了什么。 考虑使用 dict 代替。

def show_val(vals, name):
    print "Name:", name, "val:", vals[name]

vals = {'a': 1, 'b': 2}
show_val(vals, 'b')

输出:

Name: b val: 2

If you are trying to do this, it means you are doing something wrong. Consider using a dict instead.

def show_val(vals, name):
    print "Name:", name, "val:", vals[name]

vals = {'a': 1, 'b': 2}
show_val(vals, 'b')

Output:

Name: b val: 2
软的没边 2024-07-21 02:34:32

我建议描述您面临的问题,而不是询问特定解决方案的详细信息; 我想你会得到更好的答案。 我这么说是因为几乎可以肯定有更好的方法来完成您想要做的任何事情。 解决任何语言的问题通常都不需要以这种方式访问​​变量名。

也就是说,所有变量名都已经在字典中,可以通过内置函数访问 本地变量全局变量。 使用适合您正在检查的范围的正确型号。

检查这些字典的少数常见习惯之一是为了简单的字符串插值:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

这种事情往往比替代方案更具可读性,即使它需要按名称检查变量。

Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.

追星践月 2024-07-21 02:34:32

不能,因为 Python 中没有变量,只有名称。

例如:

> a = [1,2,3]
> b = a
> a is b
True

这两个变量中哪一个现在是正确的变量? ab 之间没有区别。

之前有一个类似的问题

You can't, as there are no variables in Python but only names.

For example:

> a = [1,2,3]
> b = a
> a is b
True

Which of those two is now the correct variable? There's no difference between a and b.

There's been a similar question before.

一向肩并 2024-07-21 02:34:32

这样的事情对你有用吗?

>>> def namestr(**kwargs):
...     for k,v in kwargs.items():
...       print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2

在你的例子中:

>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}

Will something like this work for you?

>>> def namestr(**kwargs):
...     for k,v in kwargs.items():
...       print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2

And in your example:

>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}
不念旧人 2024-07-21 02:34:32

通过热切求值,只要您查看变量(换句话说),变量本质上就会变成它们的值。 也就是说,Python 确实有内置的 命名空间。 例如,locals() 将返回一个字典,将函数的变量名称映射到它们的值,而 globals() 对模块执行相同的操作。 因此:

for name, value in globals().items():
    if value is unknown_variable:
        ... do something with name

请注意,您不需要导入任何内容即可访问 locals() 和 globals()。

此外,如果一个值有多个别名,则迭代命名空间只会找到第一个别名。

With eager evaluation, variables essentially turn into their values any time you look at them (to paraphrase). That said, Python does have built-in namespaces. For example, locals() will return a dictionary mapping a function's variables' names to their values, and globals() does the same for a module. Thus:

for name, value in globals().items():
    if value is unknown_variable:
        ... do something with name

Note that you don't need to import anything to be able to access locals() and globals().

Also, if there are multiple aliases for a value, iterating through a namespace only finds the first one.

烏雲後面有陽光 2024-07-21 02:34:32

对于如何读取配置参数的修订问题,我强烈建议您节省一些时间和精力并使用 ConfigParser 或(我的首选工具)ConfigObj

它们可以完成您需要的一切,并且易于使用,其他人已经担心如何让它们正常工作!

For the revised question of how to read in configuration parameters, I'd strongly recommend saving yourself some time and effort and use ConfigParser or (my preferred tool) ConfigObj.

They can do everything you need, they're easy to use, and someone else has already worried about how to get them to work properly!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文