如果在 if-else 条件下使用 assert 有什么好处?
What is the advantage if any of using assert over an if-else condition?
例如 x = "hello"。我可以不做 assert x == "hello" 而不是做 if x != "hello" 吗?使用 assert 更像 pythonic 吗?
Is using assert more pythonic?
没有。 assert
用于断言。即断言 x 的值应该是 "hello" 而不是其他任何东西。它不是像 if
这样的编程逻辑结构,而是调试关键字。正如评论者指出的那样,当断言为假时,它将抛出一个 AssertionError
异常(即发生了异常情况),如果没有被捕获则退出程序。
正如@chepner 所写,如果 __debug__
为假,它们可以在运行时被禁用,当您使用 -o
标志执行代码时会发生这种情况。
python -o myfile.py
根据the documentation,assert x == "hello"
等同于
if __debug__:
if not (x == "hello"):
raise AssertionError
__debug__
是只读变量,如果 Python 是 not 运行,则设置为 True
-O
标志,编译器可以在使用 -O
时完全省略断言检查(而不是在 运行 时不断检查 __debug__
的值)。
使用断言进行调试和测试,以便在断言失败时快速结束程序。对 必须 运行 使其余代码正常工作的代码使用 if
语句。
如果您使用 if 语句,则必须额外编写一行来显式引发异常。像这样:
x = "goodbye"
if x != "hello":
raise AssertionError("x does not equal hello!")
但这可以简化为更明显的单行 assert x == "hello", "x does not equal hello!"
当您只看一个示例时,情况还不错,但想象一下编写一个测试脚本来检查 return 数十个不同单元测试函数的值。每个断言只有一行会更清晰:
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!"
例如 x = "hello"。我可以不做 assert x == "hello" 而不是做 if x != "hello" 吗?使用 assert 更像 pythonic 吗?
Is using assert more pythonic?
没有。 assert
用于断言。即断言 x 的值应该是 "hello" 而不是其他任何东西。它不是像 if
这样的编程逻辑结构,而是调试关键字。正如评论者指出的那样,当断言为假时,它将抛出一个 AssertionError
异常(即发生了异常情况),如果没有被捕获则退出程序。
正如@chepner 所写,如果 __debug__
为假,它们可以在运行时被禁用,当您使用 -o
标志执行代码时会发生这种情况。
python -o myfile.py
根据the documentation,assert x == "hello"
等同于
if __debug__:
if not (x == "hello"):
raise AssertionError
__debug__
是只读变量,如果 Python 是 not 运行,则设置为 True
-O
标志,编译器可以在使用 -O
时完全省略断言检查(而不是在 运行 时不断检查 __debug__
的值)。
使用断言进行调试和测试,以便在断言失败时快速结束程序。对 必须 运行 使其余代码正常工作的代码使用 if
语句。
如果您使用 if 语句,则必须额外编写一行来显式引发异常。像这样:
x = "goodbye"
if x != "hello":
raise AssertionError("x does not equal hello!")
但这可以简化为更明显的单行 assert x == "hello", "x does not equal hello!"
当您只看一个示例时,情况还不错,但想象一下编写一个测试脚本来检查 return 数十个不同单元测试函数的值。每个断言只有一行会更清晰:
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!"