代码之家  ›  专栏  ›  技术社区  ›  James Brooks

在python中,如何测试变量是否为none、true或false

  •  111
  • James Brooks  · 技术社区  · 15 年前

    我有一个函数可以返回以下三项之一:

    • 成功(成功) True )
    • 失败( False )
    • 读取/分析流时出错( None )

    我的问题是,如果我不想测试 我该怎么看结果呢?以下是我目前的工作方式:

    result = simulate(open("myfile"))
    if result == None:
        print "error parsing stream"
    elif result == True: # shouldn't do this
        print "result pass"
    else:
        print "result fail"
    

    它真的和移除 == True 部分或应该添加三bool数据类型。我不想要 simulate 函数抛出一个异常,因为我只希望外部程序处理一个错误,那就是记录它并继续。

    5 回复  |  直到 9 年前
        1
  •  104
  •   PaulMcG    10 年前

    别害怕例外!让您的程序只需登录并继续,就可以轻松做到:

    try:
        result = simulate(open("myfile"))
    except SimulationException as sim_exc:
        print "error parsing stream", sim_exc
    else:
        if result:
            print "result pass"
        else:
            print "result fail"
    
    # execution continues from here, regardless of exception or not
    

    现在,您可以从Simulate方法得到更丰富的通知,了解到底出了什么问题,以防您发现错误/无错误信息不够丰富。

        2
  •  115
  •   SilentGhost    15 年前
    if result is None:
        print "error parsing stream"
    elif result:
        print "result pass"
    else:
        print "result fail"
    

    保持简单和明确。当然,你可以预先定义一本字典。

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

    如果你打算修改你的 simulate 函数包含更多返回代码,维护此代码可能会成为一个问题。

    这个 模拟 可能还会引发解析错误的异常,在这种情况下,您要么在这里捕获它,要么让它向上传播一个级别,并且如果else语句,打印位将减少到一行。

        3
  •  18
  •   S.Lott    15 年前

    从不,从不,从不说

    if something == True:
    

    从未。这太疯狂了,因为您要重复冗余地为if语句指定为冗余条件规则的内容。

    更糟的是,永远,永远,永远,永远不要说

    if something == False:
    

    你有 not . 请随意使用。

    最后,做 a == None 效率低下。做 a is None . None 是一个特殊的单例对象,只能有一个。检查一下你是否有那个物体。

        4
  •  3
  •   Community CDub    8 年前

    我想强调一下,即使在某些情况下 if expr : 还不够,因为要确保 expr True 不仅不同于 0 / None 无论如何 is 优先于 == for the same reason S.Lott mentionned for avoiding == None .

    它确实稍微更有效率,而且,蛋糕上的樱桃色,更具人类可读性。

    输入:

    from time import time
    t0 = time()
    print ( ( 1 == 1 ) == True )
    t1 = time()
    print ( ( 1 == 1 ) is True )
    t2 = time()
    print '{:e}s\n{:e}s'.format( t1-t0, t2-t1)
    

    输出:

    True
    True
    1.201630e-04s
    8.797646e-05s
    
        5
  •  2
  •   kgiannakakis    15 年前

    我认为对你的情况来说,提出例外是个更好的主意。另一种方法是返回元组的模拟方法。第一项是状态,第二项是结果:

    result = simulate(open("myfile"))
    if not result[0]:
      print "error parsing stream"
    else:
      ret= result[1]