
[英]Bash: Get value of variable from string of variable name (when string contains other characters than variable name)
[英]Is it possible to print the actual name of a variable, rather than the value it contains? [duplicate]
这个问题已经在这里有了答案:
当将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
当然,我可以手动传递一个变量名字符串,但是为了简洁起见,为了简单起见,我可以传递单个变量名。
希望这是有道理的!
在这里,追溯足够吗?
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
简短而有趣的是:您不能(真的)传递变量,只能传递值。 要传递变量,您必须传递其名称和上下文。
这通常意味着您已经知道名称,因此您可以传递名称或直接引用变量。
据我所知,在您的实际用例中,您实际上只是在检查该值。 您可以毫无问题地将该值传递给函数(如果需要,也可以传递名称-您可以静态地知道名称)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.