[Cython] What to do with modules
Robert Bradshaw
robertwb at math.washington.edu
Sun Oct 5 06:20:01 CEST 2008
On Oct 4, 2008, at 1:03 PM, Kevin Ar18 wrote:
> As I understand the Docs, you can't access c types, functions, or
> classes in a module.
I'm not quite sure I understand your question, but I'll try to answer...
Python stores its module-level in a big dict. The speed gains of
Cython are usually made by avoiding this dict storage (as well as the
wrapping everything as an object that is required to do so).
> For example, this won't work:
>
>
> somemodule.pyx
>
> cdef int a = 1
> py_get():
> return a
>
> somefile.pyx
>
> import somemodule
> cdef int b = somemodule.a
This won't, as a is not a Python object but a c global.
> print somemodule.py_get()
This should.
>
> or this:
>
> somemodule.pyx
>
> cdef extern from *:
> int a = 1
> py_get():
> return a
>
> somefile.pyx
>
> cimport somemodule
> cdef int b = somemodule.a
No, that won't either.
> So what do you do with modules that mix Cython and Python?
cdef classes live in both the C and Python namespace. cpdef functions
are accessible from both C and Python as well. In this case, you
probably need to just write
a = 1
and deal with it being a Python object so you can get at it from
Python (and it is still accessible from C). Everything accessible
from Python is also accessible from Cython.
We probably should support cimporting cdef'd global variables
(probably with the same trick as we do for functions) and it would be
nice to be able to declare variables as "public" or "readonly" as one
can do with class attributes (though the only way I could see how to
do it is the hack at http://mail.python.org/pipermail/python-list/
2007-January/422578.html or making a subtype of the module type)
- Robert
More information about the Cython-dev
mailing list