确定变量是否在Python中定义

2024-04-26 01:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Easy way to check that variable is defined in python?
How do I check if a variable exists in Python?

如何知道在运行时是否在代码中的特定位置设置了变量?这并不总是显而易见的,因为(1)变量可以有条件地设置,(2)变量可以有条件地删除。我正在寻找Perl中的defined(),或者PHP中的isset(),或者Ruby中的defined?

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

Tags: toinifthathereischeckeasy
3条回答

我认为最好避免这种情况。写得越来越清楚:

a = None
if condition:
    a = 42

'a' in vars() or 'a' in globals()

如果你想学究,你也可以检查内置
'a' in vars(__builtins__)

try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")

相关问题 更多 >