带有和不带括号的python断言 [英] python assert with and without parenthesis

查看:141
本文介绍了带有和不带括号的python断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是assert的四个简单调用:

Here are four simple invocations of assert:

>>> assert 1==2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError

>>> assert 1==2, "hi"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError: hi

>>> assert(1==2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError

>>> assert(1==2, "hi")

请注意,最后一个不会引发错误.调用带或不带括号的assert导致此行为之间有什么区别?我的做法是使用括号,但以上内容表明我不应该这样做.

Note that the last one does not raise an error. What is the difference between calling assert with or without parenthesis that causes this behavior? My practice is to use parenthesis, but the above suggests that I should not.

推荐答案

如果您通过完整的解释程序(而不是通过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").

这篇关于带有和不带括号的python断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆