python中变量名,如何在python中打印变量名?

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!

解决方案

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.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值