在 cython 中为 __contains__ 指定 libcpp.string 类型
specifying libcpp.string type for __contains__ in cython
我正在为一些 C++ 数据结构实现一个 cython 包装器,它将 C++ 字符串作为键和值。
我在 pxd 中为 class 和模板化 key/value 类型创建了 C++ 方法原型(抱歉,我从未使用过 C++,只使用过 C,所以我不确定正确的术语,如果不清楚请告诉我)
然后我在 .pyx 文件中定义一个 class 以便能够从 python 调用,它包装了 my_type[string, string]
:
的一个实例
from libcpp.string cimport string
cdef class MyType:
## This field is declared in .pxd:
# cdef my_type[string, string]* thisptr
def __cinit__(self, f=None):
self.thisptr = new my_type[string, string]()
def __init__(self, arg=None):
if hasattr(arg, 'fileno'):
self.load(arg)
elif isinstance(arg, int):
self.thisptr.resize(arg)
elif isinstance(arg, str):
with open(arg, 'rb') as f:
self.load(f)
elif arg is not None:
raise ValueError("Cannot interpret argument of type %s" % type(arg))
def __contains__(self, string item):
return self.thisptr.count(item) > 0
现在,我有另一个 .pyx 脚本,我在其中测试此功能,我在其中定义了一个 python 字符串,将字节分配给 C++ 字符串,并尝试使用 in
运算符:
from libcpp.string cimport string
def test():
m = MyType()
bytes_key = 'asdf'
bytes_val = 'jkl;'
cdef string key = bytes_key
cdef string val = bytes_val
m[key] = val
print('len(): %d' % len(m))
assert len(m) == 1, len(m)
print('__repr__(): %r' % (m, ))
assert key in m
如果我注释掉最后一行,所有内容都会编译并得到输出
len(): 0
len(): 1
__repr__(): {'asdf': 'jkl;'}
但是,在包含 assert
语句的情况下,我在编译期间遇到以下错误:
Error compiling Cython file:
------------------------------------------------------------
...
cdef string val = bytes_val
m[key] = val
print('len(): %d' % len(m))
assert len(m) == 1, len(m)
print('__repr__(): %r' % (m, ))
assert key in m
^
------------------------------------------------------------
test_internal.pyx:72:15: Invalid types for 'in' (string, MyType)
如果我将 libcpp.string.string
替换为 libc.stdint.uint16_t
,则一切正常。寻找如何解决这个问题。谢谢!
编辑
更神秘的是,如果我将有问题的行更改为 assert m.__contains__(key)
,它会编译并运行良好。
但是,如果我然后转到另一个目录,并导入 MyType,然后尝试 if not my_obj.__contains__(key)
(其中 key
是 cdef
'd 是 string
) ,我收到运行时错误,TypeError: an integer is required
...
好的,我设法使您的代码正常工作。
不过,我不确定我知道你的问题出在哪里:我唯一一次收到关于需要整数的错误是在我实现 __setitem__
方法时...
不过,我认为像这样修改函数应该可以解决问题:
def __contains__(MyType self, item):
if not isinstance(item, bytes):
item = bytes(item, "UTF-8")
return (self.thisptr.count(item) > 0)
在python3中str
和bytes
是有区别的(前者不能转成c++string
)所以需要注意转换:要求在参数中输入 string
可能最让您烦恼。
如果这还不够,这里有一个mwe:
decl.pxd
from libcpp.map cimport map as my_type
from libcpp.string cimport string
cdef class MyType:
cdef my_type[string, string]* thisptr
decl.pyx
cdef class MyType:
def __cinit__(MyType self, arg=None):
self.thisptr = new my_type[string, string]()
def __contains__(MyType self, item):
if not isinstance(item, bytes):
item = bytes(item, "UTF-8")
return (self.thisptr.count(item) > 0)
def __setitem__(MyType self, key, value):
if not isinstance(key, bytes):
key = bytes(key, "UTF-8")
if not isinstance(value, bytes):
value = bytes(value, "UTF-8")
self.thisptr[0][key] = value
def __len__(MyType self):
return self.thisptr.size()
编辑: setup.py
(我将 test.pyx
重命名为 ctest.pyx
)
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
package_data = { '': ['*.pxd'] },
ext_modules = [
Extension("ctest",
["ctest.pyx"],
language='c++',
include_dir=["."]),
Extension("decl",
["decl.pyx"],
language='c++',
include_dir=["."])]
)
EDIT2: 当然,我忘了通知你,但你不应该使用 c++ string
作为密钥:
key1 = b'asdf'
key2 = 'asdf'
assert key1 in m
assert key2 in m
我正在为一些 C++ 数据结构实现一个 cython 包装器,它将 C++ 字符串作为键和值。
我在 pxd 中为 class 和模板化 key/value 类型创建了 C++ 方法原型(抱歉,我从未使用过 C++,只使用过 C,所以我不确定正确的术语,如果不清楚请告诉我)
然后我在 .pyx 文件中定义一个 class 以便能够从 python 调用,它包装了 my_type[string, string]
:
from libcpp.string cimport string
cdef class MyType:
## This field is declared in .pxd:
# cdef my_type[string, string]* thisptr
def __cinit__(self, f=None):
self.thisptr = new my_type[string, string]()
def __init__(self, arg=None):
if hasattr(arg, 'fileno'):
self.load(arg)
elif isinstance(arg, int):
self.thisptr.resize(arg)
elif isinstance(arg, str):
with open(arg, 'rb') as f:
self.load(f)
elif arg is not None:
raise ValueError("Cannot interpret argument of type %s" % type(arg))
def __contains__(self, string item):
return self.thisptr.count(item) > 0
现在,我有另一个 .pyx 脚本,我在其中测试此功能,我在其中定义了一个 python 字符串,将字节分配给 C++ 字符串,并尝试使用 in
运算符:
from libcpp.string cimport string
def test():
m = MyType()
bytes_key = 'asdf'
bytes_val = 'jkl;'
cdef string key = bytes_key
cdef string val = bytes_val
m[key] = val
print('len(): %d' % len(m))
assert len(m) == 1, len(m)
print('__repr__(): %r' % (m, ))
assert key in m
如果我注释掉最后一行,所有内容都会编译并得到输出
len(): 0
len(): 1
__repr__(): {'asdf': 'jkl;'}
但是,在包含 assert
语句的情况下,我在编译期间遇到以下错误:
Error compiling Cython file:
------------------------------------------------------------
...
cdef string val = bytes_val
m[key] = val
print('len(): %d' % len(m))
assert len(m) == 1, len(m)
print('__repr__(): %r' % (m, ))
assert key in m
^
------------------------------------------------------------
test_internal.pyx:72:15: Invalid types for 'in' (string, MyType)
如果我将 libcpp.string.string
替换为 libc.stdint.uint16_t
,则一切正常。寻找如何解决这个问题。谢谢!
编辑
更神秘的是,如果我将有问题的行更改为 assert m.__contains__(key)
,它会编译并运行良好。
但是,如果我然后转到另一个目录,并导入 MyType,然后尝试 if not my_obj.__contains__(key)
(其中 key
是 cdef
'd 是 string
) ,我收到运行时错误,TypeError: an integer is required
...
好的,我设法使您的代码正常工作。
不过,我不确定我知道你的问题出在哪里:我唯一一次收到关于需要整数的错误是在我实现 __setitem__
方法时...
不过,我认为像这样修改函数应该可以解决问题:
def __contains__(MyType self, item):
if not isinstance(item, bytes):
item = bytes(item, "UTF-8")
return (self.thisptr.count(item) > 0)
在python3中str
和bytes
是有区别的(前者不能转成c++string
)所以需要注意转换:要求在参数中输入 string
可能最让您烦恼。
如果这还不够,这里有一个mwe:
decl.pxd
from libcpp.map cimport map as my_type
from libcpp.string cimport string
cdef class MyType:
cdef my_type[string, string]* thisptr
decl.pyx
cdef class MyType:
def __cinit__(MyType self, arg=None):
self.thisptr = new my_type[string, string]()
def __contains__(MyType self, item):
if not isinstance(item, bytes):
item = bytes(item, "UTF-8")
return (self.thisptr.count(item) > 0)
def __setitem__(MyType self, key, value):
if not isinstance(key, bytes):
key = bytes(key, "UTF-8")
if not isinstance(value, bytes):
value = bytes(value, "UTF-8")
self.thisptr[0][key] = value
def __len__(MyType self):
return self.thisptr.size()
编辑: setup.py
(我将 test.pyx
重命名为 ctest.pyx
)
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
package_data = { '': ['*.pxd'] },
ext_modules = [
Extension("ctest",
["ctest.pyx"],
language='c++',
include_dir=["."]),
Extension("decl",
["decl.pyx"],
language='c++',
include_dir=["."])]
)
EDIT2: 当然,我忘了通知你,但你不应该使用 c++ string
作为密钥:
key1 = b'asdf'
key2 = 'asdf'
assert key1 in m
assert key2 in m