Python编译器是否有可能优化掉一些整数运算?

Rou*_*wer 4 python compiler-construction

灵感来自这个关于Python缓存小整数的问题.

Python编译器是否有可能在编译时用-6替换(0 - 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()
Run Code Online (Sandbox Code Playgroud)

我的Python详细信息,以防这与实现有关:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 11

首先,您不应该使用is比较整数值来检测优化.这与任何事情无关,正如你所链接的问题所解释的那样.如果您想知道对您的函数执行了哪些优化,请使用dis模块(在2.7.2中修复您的-1拼写错误后):

>>> import dis
>>> 
>>> def test_integers():
...     print "-6 is -6 ?", -6 is -6 # True
...     print "(0-6) is -6 ?", (0 - 6) is -6 # False
... 
>>> dis.dis(test_integers)
  2           0 LOAD_CONST               1 ('-6 is -6 ?')
              3 PRINT_ITEM          
              4 LOAD_CONST               2 (-6)
              7 LOAD_CONST               2 (-6)
             10 COMPARE_OP               8 (is)
             13 PRINT_ITEM          
             14 PRINT_NEWLINE       

  3          15 LOAD_CONST               3 ('(0-6) is -6 ?')
             18 PRINT_ITEM          
             19 LOAD_CONST               6 (-6)
             22 LOAD_CONST               2 (-6)
             25 COMPARE_OP               8 (is)
             28 PRINT_ITEM          
             29 PRINT_NEWLINE       
             30 LOAD_CONST               0 (None)
             33 RETURN_VALUE        
Run Code Online (Sandbox Code Playgroud)

并且你看到减法实际上优化了.你也可以看到其他一些:

>>> def f():
...     x = 1+2
...     x = 2-3
...     x = 3*4
...     x = 4/5
...     x = 5**6
... 
>>> dis.dis(f)
  2           0 LOAD_CONST               7 (3)
              3 STORE_FAST               0 (x)

  3           6 LOAD_CONST               8 (-1)
              9 STORE_FAST               0 (x)

  4          12 LOAD_CONST               9 (12)
             15 STORE_FAST               0 (x)

  5          18 LOAD_CONST               4 (4)
             21 LOAD_CONST               5 (5)
             24 BINARY_DIVIDE       
             25 STORE_FAST               0 (x)

  6          28 LOAD_CONST              10 (15625)
             31 STORE_FAST               0 (x)
             34 LOAD_CONST               0 (None)
             37 RETURN_VALUE        
Run Code Online (Sandbox Code Playgroud)