Modules written in Cython usually comes with a setup.py
script that compiles Cython source codes into native shared libary. For whom not so familiar with Python’s packaging and distributing toolchains, such step is sometimes scary, and turns out to be a stumbling block for Cython freshmen. Moreover, the workflow, “run setup.py -> debug -> edit .pyx files -> run setup.py”, is also less convenient and troublesome for fast iterating projects.
pyximport
is a handy tool from Cython official, provided to address the above problem. The module enables users to “directly import” .pyx
files, with no explicit setup.py
required. Let’s start from an example here. Say we have two files residing in the same directory:
# main.py
import pyximport
# hl: begin
pyximport.install(language_level=3)
# hl: end
import foo
print(foo.func(3))
# foo.pyx
cpdef int sqr(int x):
return x * x
The magical highlighted
line registers some import hooks to let Python recognize .pyx
files. When the .pyx
files imported for the first time or modified later, pyximport
compiles or re-compiles them behind the scene automatically.