【发布时间】:2012-07-14 05:06:31
【问题描述】:
灵感来自 this 关于 Python 缓存小整数的问题。
Python 编译器是否可以在编译时将 (0 - 6) 替换为 -6?下面的代码表明它没有。如果不可能,为什么不呢?我不认为0、- 或6 的含义在运行时会有所不同。
如果可以,为什么 CPython 不这样做?
# test_integers.py
def test_integers():
print "-6 is -6 ?", -6 is -6 # True
print "(0 - 6) is -6 ?", (0 - 6) is -6 # False
# import_test_integers.py
import test_integers
test_integers.test_integers()
我的 Python 详细信息,以防这非常依赖于实现:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
【问题讨论】:
-
FWIW:这种类型的优化被称为“常量折叠”。 (我不知道 CPython 是否这样做。)
标签: python compiler-construction