Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

design of python: why is assert a statement and not a function?

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?

According to the docs, assert expression1, expression2 is expanded to

if __debug__:
    if not expression1: raise AssertionError(expression2)

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.

If assert were a function, you could write:

assert(some_long_condition,
       "explanation")

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

SyntaxWarning: assertion is always true, perhaps remove parentheses?

The correct way to write it is

assert some_long_condition, 
       "explanation"

which is arguably less pretty.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  1. Cannot be reassigned to a user function, meaning it can be effectively disabled at compile time as @mgilson pointed out.
  2. The evaluation of the second, optional parameter is deferred until if/when the assertion fails. Awkward to do that with functions and function arguments (would need to pass a lambda.) Not deferring the evaluation of the second parameter would introduce additional overhead.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...