开发者

How can I check to see if a variable exists?

I want to check if variables named component + "_STATUS" or + "_DESC" exist.

I tried the following, but it won't work. So, here's my code:

Components = ['SAVE_DOCUMENT', \
'GET_DOCUMENT', \
'DVK_SEND', \
'DVK_RECEIVE', \
'GET_USER_INFO', \
'NOTIFICATIONS', \
'ERROR_LOG', \
'SUMMARY_STATUS']

for Component in Co开发者_运维问答mponents:
    try:
        eval(Component + "_STATUS")
        eval(Component + "_DESC")
    except NameError:
        print "Missing component " + Component + " information!"
        sys.exit(StateUnknown)


I might be wrong but i think that you can do this the following way(without usign eval - because it is not a very good to use it):

Components = ['SAVE_DOCUMENT', 'GET_DOCUMENT', 'DVK_SEND', 'DVK_RECEIVE', 'GET_USER_INFO', 'NOTIFICATIONS', 'ERROR_LOG', 'SUMMARY_STATUS']
missed = [x for x in Components if x + "_STATUS" not in locals() or x + "_DESC" not in locals()]
if missed:
    print "Missing components: {0:}".format(missed)
    sys.exit(StateUnknown)        

In case you need to check variable presence in local scope you can use locals(), otherwise you can use globals()


>>> f = 1
>>> globals()
{'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', 'f': 1, '__doc__': None, '__package__': None}
>>> 'f' in globals()
True
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜