Determine if variable is defined in Python [duplic

2019-01-08 02:53发布

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

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

7条回答
爷的心禁止访问
2楼-- · 2019-01-08 03:43
try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope
查看更多
登录 后发表回答