python variable name_如何在python中打印變量名?(復制)

This question already has an answer here:

這個問題已經有了答案:

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

假設有一個變量,它等於2。如何訪問變量的名稱?一些相當於

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

這樣做的原因是。我正在運行一些數據分析的東西,我用多個參數調用這個程序,我想在運行時調整,或者不調整。我在最后一次運行的.config文件中讀取了我使用的參數。

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.

我的問題來了,因為當涉及到編寫字典時,這些值已經被掃描到。如果需要一個參數,我將運行get_param,它訪問該文件並找到參數。

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!

我想我將通過讀取.config文件並從中生成字典來避免所有問題。我本來是為了……我不再記得的原因。完善的情況更新我的代碼!

8 个解决方案

#1

71

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.

我希望它能激勵你重新評估你的問題,並尋找另一種方法。

#2

43

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.

正如@rbright已經指出的,無論你做什么,可能都有更好的方法。

#3

13

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

您不能,因為Python中沒有變量,只有名稱。

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.

哪一個是正確的變量?a和b沒有區別。

There's been a similar question before.

之前也有過類似的問題。

#4

9

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

#5

6

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.

也就是說,所有變量名都已經在字典中了,這些字典可以通過內置函數local和globals訪問。在檢查的范圍內使用正確的方法。

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.

這類東西往往比其他選項更具可讀性,盡管它需要按名稱檢查變量。

#6

2

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__ =

__name__ = '__main__'

__doc__ = None

namestr =

choice = {'data': None, 'key': 24}

#7

2

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.

對於如何在配置參數中讀取的修改問題,我強烈建議您節省一些時間和精力,並使用ConfigParser或(我的首選工具)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!

他們可以做你需要的任何事情,他們很容易使用,而其他人已經開始擔心如何讓他們正常工作!

#8

2

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:

有了熱切的評價,當你看到這些變量時,它們就會轉化為它們的價值(轉述)。也就是說,Python確實有內置的名稱空間。例如,local()將返回一個字典,將函數的變量名稱映射到它們的值,而globals()對模塊執行相同的操作。因此:

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.

另外,如果一個值有多個別名,那么遍歷名稱空間只會找到第一個。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值