[Cython] Bug in list comprehension

Leandro Pereira de Lima e Silva leandro at limaesilva.com.br
Fri Oct 16 10:04:33 EDT 2015


Hello,

I've think I've found a bug in Cython (or is this just a funny feature?).
The error occurs when the variable name used as source for the iteration is
also used as a value.

Given the files test1.pyx (cython) and test2.py (python):

test1.pyx:
def test():
    x = range(10)
    return [x for x in x]

test2.py:
def test():
    x = range(10)
    return [x for x in x]

The results in running them are:
>>> import test1, test2
>>> test1.test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test1.pyx", line 4, in test1.test
(/Users/leandro/.pyxbld/temp.macosx-10.6-intel-3.4/pyrex/test1.c:666)
    return [x for x in x]
UnboundLocalError: local variable 'x' referenced before assignment
>>> test2.test()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

A regular for loop will behave correctly:

code:
def test():
    x = range(10)
    ret = []
    for x in x:
        ret.append(x)
    return ret

result:
>>> import test1, test2
>>> test1.test()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test2.test()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Cheers, Leandro
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cython-devel/attachments/20151016/1f1b4f30/attachment.html>


More information about the cython-devel mailing list