One important reason why assertions should only be used for self-tests of the program is that assertions can be disabled at compile time.
If Python is started with the -O option, then assertions will be stripped out and not evaluated. So if code uses assertions heavily, but is performance-critical, then there is a system for turning them off in release builds.
依靠断言不是个好主意。使用断言作为流控制不是一个好主意。原因正如你所描述的:它们可以被禁用。documentation简单地说:
断言是用于调试的,在生产代码中不可依赖。你知道吗
断言是为了捕捉错误,而不是为了流控制。因此,对于一个乐观主义者来说,去掉这些bug是完全有效的,因为当你的代码发布时,这些bug应该已经被删除了。
如果您将它们用作一般用途的异常引发器,我建议您使用它们是错误的。你知道吗
在Python Wiki上有一个很好的页面讨论这个问题,我特别指出最后一点:
相关问题 更多 >
编程相关推荐