“优化”.pyo文件不安全吗?

2024-03-28 21:28:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我惊恐地发现python -O去掉了assert语句。我在任何地方都使用断言,并且我认为断言(像一般的例外)是流控制的一种形式。你知道吗

Python人:python -O.pyo文件被认为是安全的吗?依赖资产是否不安全?你知道吗


Tags: 文件地方assert断言语句资产形式pyo
2条回答

依靠断言不是个好主意。使用断言作为流控制不是一个好主意。原因正如你所描述的:它们可以被禁用。documentation简单地说:

Assert statements are a convenient way to insert debugging assertions into a program

断言是用于调试的,在生产代码中不可依赖。你知道吗

断言是为了捕捉错误,而不是为了流控制。因此,对于一个乐观主义者来说,去掉这些bug是完全有效的,因为当你的代码发布时,这些bug应该已经被删除了。

如果您将它们用作一般用途的异常引发器,我建议您使用它们是错误的。你知道吗

Python Wiki上有一个很好的页面讨论这个问题,我特别指出最后一点:

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.

相关问题 更多 >