In Python how should I test if a variable is None, True or False

前端 未结 6 1127
野的像风
野的像风 2020-11-30 20:16

I have a function that can return one of three things:

  • success (True)
  • failure (False)
  • error reading/parsing stream
6条回答
  •  鱼传尺愫
    2020-11-30 21:02

    if result is None:
        print "error parsing stream"
    elif result:
        print "result pass"
    else:
        print "result fail"
    

    keep it simple and explicit. You can of course pre-define a dictionary.

    messages = {None: 'error', True: 'pass', False: 'fail'}
    print messages[result]
    

    If you plan on modifying your simulate function to include more return codes, maintaining this code might become a bit of an issue.

    The simulate might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.

提交回复
热议问题