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

前端 未结 4 666
滥情空心
滥情空心 2020-12-13 12:26

In Python, assert is a statement, and not a function. Was this a deliberate decision? Are there any advantages to having assert be a statem

4条回答
  •  醉酒成梦
    2020-12-13 12:38

    One of the wonderful things about assert in python and in other languages (specifically C) is that you can remove them to optimize your code by just adding the correct #define (optionally on the commandline with any compiler I've ever used) or optimization flags (-O in python). If assert became a function, this feature would be impossible to add to python as you don't know until runtime whether you have the builtin assert function or user-defined function of the same name.


    Also note that in python, function calls are reasonably expensive. Replacing inline with the code if __debug__: ... is probably a lot more efficient than doing a function call which could be significant if you put an assert statement in a performance critical routine.

提交回复
热议问题