python的设计:为什么断言是一个语句而不是一个函数? [英] design of python: why is assert a statement and not a function?
问题描述
在 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?
根据 docs,assert expression1, expression2
扩展为
if __debug__:
if not expression1: raise AssertionError(expression2)
文档还说当在编译时请求优化时,当前的代码生成器不会发出断言语句的代码."在不知道细节的情况下,似乎需要一个特殊情况才能使这成为可能.但是,一种特殊情况也可用于优化对 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"
这可以说不那么漂亮.
推荐答案
将 assert 作为语句(和保留字)而不是函数有什么好处吗?
Are there any advantages to having assert be a statement (and reserved word) instead of a function?
- 不能重新分配给用户函数,这意味着它可以在编译时被有效地禁用,正如@mgilson 指出的那样.
- 第二个可选参数的评估被推迟到断言失败时.使用函数和函数参数(需要传递一个 lambda)来做这件事很尴尬.不推迟对第二个参数的评估会引入额外的开销.
这篇关于python的设计:为什么断言是一个语句而不是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!