python的设计:为什么断言一个语句而不是一个函数? [英] design of python: why is assert a statement and not a function?

查看:117
本文介绍了python的设计:为什么断言一个语句而不是一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,assert是语句,而不是函数.这是一个故意的决定吗?将assert用作语句(和保留字)而不是函数有什么好处?

In Python, assert is a statement, and not a function. Was this a deliberate decision? Are there any advantages to having assert be a statement (and reserved word) instead of a function?

根据 the 文档还说:当在编译时请求优化时,当前代码生成器不会为assert语句生成任何代码."在不知道细节的情况下,似乎需要特殊情况才能实现这一点.但是,然后,也可以使用特殊情况来优化对assert()函数的调用.

The docs also say that "The current code generator emits no code for an assert statement when optimization is requested at compile time." Without knowing the details, it seems like a special case was required to make this possible. But then, a special case could also be used to optimize away calls to an assert() function.

如果assert是一个函数,则可以编写:

If assert were a function, you could write:

assert(some_long_condition,
       "explanation")

但是因为assert是一条语句,所以元组总是求值为True,并且 你得到

But because assert is a statement, the tuple always evaluates to True, and you get

SyntaxWarning: assertion is always true, perhaps remove parentheses?

正确的书写方式是

assert some_long_condition, \
       "explanation"

可以说不那么漂亮.

推荐答案

断言是语句(和保留字)而不是函数是否有任何优势?

Are there any advantages to having assert be a statement (and reserved word) instead of a function?

  1. 无法重新分配给用户功能,这意味着可以如@mgilson所指出的那样在编译时有效地禁用它.
  2. 第二个可选参数的求值被推迟到断言失败时.笨拙地使用函数和函数参数(需要传递lambda.)不推迟对第二个参数的求值会带来额外的开销.

这篇关于python的设计:为什么断言一个语句而不是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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