获取python变量的名称

时间:2014-10-27 15:05:58

标签: python python-2.7

def f(s)
  print <name of s> = s

我希望为f(hello)输出“hello = 10”,因为变量hello的值为10.

问题是如何获取变量的变量名称,即<name of s>

这是出于调试目的。 说给出一个新的陈述s=2

f(s)在新语句打印s=0之前,如果s最初为0 f(s)s=2将会打印def f(name,value) print "%s=%s"%(name,str(value))

我可以轻松地写道:

f("s",s)

并将其用作{{1}},但这需要我输入两个参数,这更加麻烦。

4 个答案:

答案 0 :(得分:7)

我不确定它是否真的值得,但是使用来自框架的信息来进行带位置参数的简单函数调用你可以这样做:

import inspect

def hello(s1, s2, s3, s4):
    args = inspect.getargspec(hello).args
    line = inspect.getouterframes(inspect.currentframe())[1][4][0]
    actual_args = map(str.strip, line[line.index('(')+1: line.index(')')].split(','))
    for x, y in zip(args, actual_args):
        print "value of {} is {}".format(y, locals()[x])

a, b, c, d = 1, 2, 3, 4
hello(a, b, c, d)

输出:

value of a is 1
value of b is 2
value of c is 3
value of d is 4

答案 1 :(得分:3)

您可以(可能)使用traceback模块执行此操作。

import traceback
def some_func(x):
    stack = traceback.extract_stack()
    calling = stack[-2]
    func_call_str = calling[-1]
    print func_call_str

我可能不知道很多警告,但至少打电话some_func(hello)应打印some_func(hello),您可以继续提取变量名称&#34 ;使用字符串提取方法。

答案 2 :(得分:-1)

如果你的函数只有一个参数;那么你可以这样做。

def f(s):
    var, val = locals.items()[0]  # `var` will always have value 's', so no much difference here.
    print "{} = {}".format(var, val)

在你的情况下,传递参数(实际参数)名称一旦传入函数(Formal参数)就不可用。

答案 3 :(得分:-2)

你可以这样做:

def func(**kwargs):
    for key in kwargs:
        print 'Var <%s> with value <%s>' % (key, kwargs[key])

>>> func(say=2, qqq=3)
    Var <say> with value <2>
    Var <qqq> with value <3>