[Cython] Bug with inlined functions that access globals

Erik Bray erik.m.bray at gmail.com
Fri Nov 24 08:48:43 EST 2017


On Fri, Nov 24, 2017 at 2:16 PM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Erik Bray schrieb am 24.11.2017 um 13:44:
>> I think maybe I've seen this brought up once or twice before in the
>> past, but with no real discussion.  There is a slightly unpythonic
>> problem with using cpdef inline functions defined in a .pxd file that
>> happen to access global variables.  For example:
>>
>> $ cat foo.pxd
>> FOO_A = 1
>>
>> cpdef inline foo():
>>     return FOO_A
>
> Hmm, I might be missing something, but it feels like globals in a .pxd file
> should not be allowed in the first place - unless there is a .pyx file for
> them. But that's difficult to prohibit, given that the .pyx file is not
> needed at compile time, and might not be there at all, just the readily
> compiled module (and maybe not even that).
>
> And I don't see why Python globals should be allowed in .pxd files at all.
>
> So - it seems probably difficult to improve the first case. Regarding your
> actual example, however, if there is really no use case for Python globals
> in .pxd files, then we should better disallow them.

That would be an acceptable resolution, though I believe there is a
use case for it.  If you take some function that was originally
defined in a .pyx module, but you want to be able to inline it, then
one is forced to rewrite it in some way if it in any way relied on
some module-level globals (which is a normal thing to do).  So it's a
problem of the implementation details driving what language features
one is allowed to use.  This is less than ideal...

Anyways there's really two issues here:

1) Python globals in .pxd files, which you're saying should be
disallowed--I have to wonder if there isn't some way to make that make
sense, but I don't feel strongly about it.
2) Non-local variables in functions defined in .pxd files--again these
should either be allowed by some mechanism, or entirely disallowed
since otherwise the result is either the function breaks with a
NameError, or behaves wildly unexpectedly if it gets dropped into a
module that happens to have a global of the same name


More information about the cython-devel mailing list