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

前端 未结 6 1100
野的像风
野的像风 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:15

    I would like to stress that, even if there are situations where if expr : isn't sufficient because one wants to make sure expr is True and not just different from 0/None/whatever, is is to be prefered from == for the same reason S.Lott mentionned for avoiding == None.

    It is indeed slightly more efficient and, cherry on the cake, more human readable.

    In [1]: %timeit (1 == 1) == True
    38.1 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    
    In [2]: %timeit (1 == 1) is True
    33.7 ns ± 0.141 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    

提交回复
热议问题