为什么断言没有被大量使用? [英] Why assert is not largely used?

查看:163
本文介绍了为什么断言没有被大量使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Python的断言声明是一个很好的方法抓住 不应该发生的情况 。当代码被信任为正确时,可以通过Python优化来删除它。



似乎是在调试模式下运行Python应用程序的完美机制。但是看几个Python项目,如django,扭曲和zope,几乎从未使用 assert 。为什么会发生这种情况?



为什么在Python社区中不会经常使用断言语句?

解决方案

我猜, assert 不常用的主要原因是没有人使用Python的优化的模式。



Asserts是一个很好的工具,用于检测编程错误,防范意外情况,但所有这些错误检查都带有成本。在编译语言(如C / C ++)中,这并不重要,因为断言只能在调试版本中启用,并且完全从发行版本中删除。



在Python中,另一方面,在调试发布模式之间没有严格的区别。解释器具有优化标志( -O ),但目前这并不是实际优化字节码,而只能删除断言。



因此,大多数Python用户只是忽略 -O 标志,并以正常模式运行其脚本,这是调试模式,因为断言被启用,并且 __ debug __ True ,但被认为是生产就绪。 p>

也许更明智地切换逻辑,即默认情况下是优化,只能在显式的调试模式(*)中使能断言,但是我猜这会混淆很多用户,我怀疑我们会看到这样的变化。



((*)这是例如Java VM如何执行的,具有 -ea (启用断言)开关。)


I found that Python's assert statement is a good way to catch situations that should never happen. And it can be removed by Python optimization when the code is trusted to be correct.

It seems to be a perfect mechanism to run Python applications in debug mode. But looking at several Python projects like django, twisted and zope, the assert is almost never used. So, why does this happen?

Why are asserts statements not frequently used in the Python community?

解决方案

I guess the main reason for assert not being used more often is that nobody uses Python's "optimized" mode.

Asserts are a great tool to detect programming mistakes, to guard yourself from unexpected situations, but all this error checking comes with a cost. In compiled languages such as C/C++, this does not really matter, since asserts are only enabled in debug builds, and completely removed from release builds.

In Python, on the other hand, there is no strict distinction between debug and release mode. The interpreter features an "optimization flag" (-O), but currently this does not actually optimize the byte code, but only removes asserts.

Therefore, most Python users just ignore the -O flag and run their scripts in "normal mode", which is kind of the debug mode since asserts are enabled and __debug__ is True, but is considered "production ready".

Maybe it would be wiser to switch the logic, i.e., "optimize" by default and only enable asserts in an explicit debug mode(*), but I guess this would confuse a lot of users and I doubt we will ever see such a change.

((*) This is for example how the Java VM does it, by featuring a -ea (enable assertions) switch.)

这篇关于为什么断言没有被大量使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆