如果有的话,使用 assert 比使用 if-else 条件有什么好处?

问题描述 投票:0回答:2

例如 x = "hello". 我可以不做 assert x == "hello",而是做 if x != "hello". 使用 assert 是否更符合 pythonic 的要求?

python assert
2个回答
4
投票

根据 文件, assert x == "hello" 相当于

if __debug__:
    if not (x == "hello"):
        raise AssertionError

__debug__ 是一个只读变量,设置为 True 如果Python是 随行 -O 标志,编译器可以完全省略断言检查,当 -O 的值(而不是不断地检查 __debug__ 在运行时)。)

使用断言进行调试和测试,在断言失败时快速结束程序。使用 "断言 "来进行调试和测试,如果断言失败,则快速结束程序。if 语句的代码,这些代码 必须 运行,使你的其他代码能够正常工作。


0
投票

使用 assert 是否更加 pythonic?

不是。assert assert 是用于断言,即断言 x 的值应该是 "hello",而不是其他。它不是一个编程逻辑结构,比如 if 而是一个调试关键字。正如评论者所指出的,当断言为假时,它将抛出一个 AssertionError 异常(即发生了特殊的事情),如果没有被捕获,则退出程序。

就像 @chepner 写的那样,它们可以在运行时被禁用,如果 __debug__ 是假的,当你用 -o 标志,如果你使用if语句,你就必须额外写一行来明确地引发异常。

python -o myfile.py

0
投票

如果你使用if语句,你将不得不写一行额外的行来显式地引发异常。就像这样。

x = "goodbye"

if x != "hello":
  raise AssertionError("x does not equal hello!")

但这可以简化为一行更明显的单行的 assert x == "hello", "x does not equal hello!"

当你只看一个例子时,这并不那么糟糕,但想象一下,写一个测试脚本,检查几十个不同的单元测试函数的返回值。每个断言只有一行,就干净多了。

assert get_user_id("dataguy") == 1, "get_user_id test failed!"
assert get_lat_lon("test_user") == (-71.1,42.2), "get_lat_lon test failed!"
assert register_user("new_user","email") == "success!", "register_user test failed!"
© www.soinside.com 2019 - 2024. All rights reserved.