Dan Dinh
Dan Dinh

Reputation: 8609

Cython: How to import global variables from a module?

A module with global C variable:

# mymod.pyx (compiled to mymod.so)
cdef int myvar

How to access myvar from another file?
Scenario 1:

# myapp.pyx (import module only)
import mymod
print(mymod.myvar) # myvar is Python object, not int

Scenario 2:

# myapp.pyx (import variable directly)
from mymod import myvar # Error, no such myvar as Python var

Scenario 3:

# myapp.pyx (import with cimport, needs .pxd file)
from mymod cimport myvar

I wish to use .pyx files only, if possible. Unless there are no choices, I may use .pxd files, how to move myvar to .pxd file in such case?

Upvotes: 1

Views: 601

Answers (1)

Dan Dinh
Dan Dinh

Reputation: 8609

Turned out that cdef globals in a module must be in .pxd files.

For example:

# submod.pyx
some code...
# submod.pxd
cdef int myvar
# mod.pyx
cimport submod
print(submod.myvar)
# app.py
import mod

Upvotes: 2

Related Questions