且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有和不带括号的python断言

更新时间:2022-12-27 13:17:01

如果您通过完整的解释程序(而不是通过IDLE)运行该命令,则最后一个assert会给您一个警告(SyntaxWarning: assertion is always true, perhaps remove parentheses?).因为assert是关键字而不是函数,所以实际上您将元组作为第一个参数传递而省略了第二个参数.

The last assert would have given you a warning (SyntaxWarning: assertion is always true, perhaps remove parentheses?) if you ran it through a full interpreter, not through IDLE. Because assert is a keyword and not a function, you are actually passing in a tuple as the first argument and leaving off the second argument.

回想一下,非空元组的计算结果为True,并且由于断言消息是可选的,因此您在编写assert(1==2, "hi")时实际上已经调用了assert True.

Recall that non-empty tuples evaluate to True, and since the assertion message is optional, you've essentially called assert True when you wrote assert(1==2, "hi").