tCommon 导入cython

tCommon imports cython

我有一个文件结构

[CODE DIR]
- foo_1.pyx
- foo_1.pxd
- ...
- foo_n.pyx

大多数文件共享一些导入语句,即 from cython cimport [somePackage]

问题

我想要一个通用文件 foo_common.pyx,其中包含跨 foo_x.pyx 文件的共享导入,而无需复制大部分文件。 foo_common.pyx 将包含例如

[foo_common.pyx]
cimport numpy as np
from cython.parallel cimport prange 
....

我尝试在 pyxpxd 文件中堆叠一些通用定义,但 cython 似乎只能看到 class 或其他定义,但看不到。在 cython 中是否有可能有一个通用的 'header-like' 文件来读取导入语句?

澄清

我有定义文件 definitions.pxd :

[definitions.pxd]
cimport cython

我还有一些其他文件foo_1.pyx

[foo_1.pyx]
from definitions cimport *

@cython.cdivision(True)
cdef doing_something (int x):
     return x

会错误地指出 cdef function cannot take arbitrary decorators。 将 cimport 更改为 include 将 运行 完美无缺。为什么这种行为不同?

事后看来,我找到了关于 pxd 中共享定义的内容的答案:

It cannot contain the implementations of any C or Python functions, or any Python class definitions, or any executable statements. 来自 here。似乎 include 是可行的方法,因为 cimport / import 语句忽略了任何其他定义;只有 C/C++ 相关定义。

Cython 有两种在多个 pyx 文件之间共享信息的方法:

  • 使用 cimport 机制是 python-like,更复杂的方式类似于 import
  • 使用 include 对应于将 header 的内容转储到另一个文件的低级 C-ish 方式,即 #include <xxx>.

您要找的是第二个选项。例如在将 common.pxi 定义为:

# common.pxi
from libc.stdint cimport  int64_t   
ctypedef double float64
...

可用于不同的pyx-files、a.pyx:

# a.pyx:
include "common.pxi"  # definitions of float64_t, int64_t are now known

# float64_t, int64_t are used:
cdef doit_a(float64_t a, int64_t b):
    ....

b.pyx:

# b.pyx:
include "common.pxi"  # definitions of float64_t, int64_t are now known

# float64_t, int64_t are used:
cdef doit_a(float64_t a, int64_t b):
    ....

虽然将 pxi 文件用于常见的 typedefcimports,但也将 pyx-file 分成多个子部分,这些都是有效的用法 - 对于其他场景pxd-文件是更好的选择,有时是唯一的(理智的)选择(共享 cdef-cdef class 的界面)。

pxd-files 的一个优点是可以更好地控制导入的内容,类似于 import 可以通过

导入所有内容
# definitions are in common.pxd
from common cimport *

但也可以选择只导入一些名称。