列表理解结果在Cython和CPython之间有所不同

时间:2017-10-08 17:15:55

标签: python python-3.x cython compatibility

这是我运行的程序(为了演示而简化之后):

#!/usr/bin/python3
ALPHABET = 'AB'
word='A'
assert not [l for l in word if l not in ALPHABET] , "Failed"

我正在使用Linux / Ubuntu。我有cpython 3.5。

Cpython (./demo.py) : no assert, ok.
pypy3 (pypy3 demo.py) : no assert, ok. 
nuitka (nuitka --run --python-version=3.5 demo.py) : no assert, ok.

但是,对于cython:

cython -3 --embed demo.py
gcc -I/usr/include/python3.5m -O3 -o demo demo.c -lpython3.5m -lm -lutil -ldl
./demo

我明白了:

Traceback (most recent call last):
  File "demo.py", line 5, in init demo (demo.c:736)
    assert not [l for l in word if l not in ALPHABET] , "Failed"
AssertionError: Failed

似乎是理解列表,当在"断言不"时,不被评估为错误

=>我错过了什么???

1 个答案:

答案 0 :(得分:2)

这似乎是cython中的一个错误,我已经在他们的跟踪器here上报告了它

我已将复制简化为:

assert not [l for l in [1] if False], 'FAIL'

cython在编译时错误地将其优化为raise AssertionError('FAIL')

  /* "demo.py":2
 * #!/usr/bin/python3
 * assert not [l for l in [1] if False], 'FAIL'             # <<<<<<<<<<<<<<
 */
  #ifndef CYTHON_WITHOUT_ASSERTIONS
  if (unlikely(!Py_OptimizeFlag)) {
    if (unlikely(!0)) {
      PyErr_SetObject(PyExc_AssertionError, __pyx_n_u_FAIL);
      __PYX_ERR(0, 2, __pyx_L1_error)
    }
  }
  #endif