是否可以打印变量的实际名称,而不是它包含的值?

时间:2013-09-10 15:43:35

标签: python

当我使用带有我不熟悉的库的ctypes时(在这个特定的情况下,Windows API),我倾向于非常积极地检查每个小步骤的失败,因为Windows API只返回Null,而不是抛出任何类型错误。

所以,我有很多行看起来像这样:

myVariableName = windll.user32.SomeWinAPIFuncThatReturnsZeroIfItFails()
if not myVariableName: print "Failed to create myVariableName"

在重复编码时,我重复了一下kazzilion。

如果我可以将上面的检查包装到checkSuccess()函数中,这将是非常好的,它只需要检查变量的名称。

的内容
def check_success(var_name):
    if not var_name:
        print "failed to create %s" % var_name # <-- but the actual variable name; not the value
        sys.exit()
    return True

当然,我可以手动传入变量名称的字符串,但是为了清洁和样板文件,我可以传递单个变量名称,这很酷。

希望这是有道理的!

2 个答案:

答案 0 :(得分:2)

这里有足够的回溯吗?

myVariableName = windll.user32.SomeWinAPIFuncThatReturnsZeroIfItFails()
if not myVariableName: raise ValueError

当它被提升时,你会看到:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    my_function()
  File "main.py", line 3, in my_function
    if not myVariableName: raise ValueError
ValueError

您可以编写一个函数来帮助您:

def verify_non_zero(x):
    if x == 0: raise ValueError
    return x

然后:

myVariableName = verify_non_zero(windll.user32.SomeWinAPIFunc())

哪会给你回溯:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    myVariableName = verify_non_zero(windll.user32.SomeWinAPIFunc())
  File "<pyshell#6>", line 2, in verify_non_zero
    if x == 0: raise ValueError

答案 1 :(得分:1)

简短而甜蜜的是:你不能(真的)传递变量,只能传递值。要传递变量,您必须传递其名称及其上下文。

这通常意味着您已经知道了名称,因此您可以直接传递名称,或直接引用该变量。

在您的实际用例中,据我所知,您实际上只是检查值。您可以将该值传递给函数,没问题(如果需要,也可以传递名称 - 您可以静态地知道名称)。

相关问题