[Cython] prevent comprehension variables from leaking

Stefan Behnel stefan_ml at behnel.de
Thu Dec 18 17:51:07 CET 2008


Hi,

I think this change might be a bit controversial, so I would like to hear
some comments on it. I added a transform that keeps the run variable in
comprehensions from leaking by replacing it with a temp variable. This
mimics the way comprehensions work in Py3 and generator expressions work in
Py2. I.e. this will no longer work:

    [x for x in range(10)]
    print x

Well, it may still work, but it will then print "None" instead of "9", as x
is not initialised outside of the loop. Even worse, BTW, it will currently
print an arbitrary integer if 'x' is an uninitialised C int...

Doing this change, I noticed that this makes it somewhat tricky to set a
type for 'x'. This still works:

    cdef int x
    [x for x in range(10)]

and it still makes 'x' and int, but it feels somewhat wrong that you have
to do it this way. We might be able to allow something like this:

    [x for <int>x in range(10)]

but to me that doesn't feel much better.

Any comments or ideas?

Would it be enough to document this behaviour? Something like: "the
original value of the loop variable in a comprehension is restored on exit"
or something like that?

Stefan


More information about the Cython-dev mailing list