python - 在 Python 中使 SWIG 包装内置类 "hashable"

标签 python python-2.7 hashmap swig

我使用 SWIG将我们的 C++ 库暴露给 Python。出于性能原因,我有兴趣将一些包装切换为使用 SWIG 的 -builtin选项,它删除了 Python 代理对象的层。

但是,包装类不能再用于 Python 集中或作为 Python 字典中的键。它是不可散列的!

>>> wrapped_object = WrappedObject()
>>> hash(wrapped_object)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'structure.WrappedObject'

我已经为我的类定义了 __hash__()__eq__()__ne__() 方法。

>>> wrapped_object.__hash__
<built-in method __hash__ of structure.WrappedObject object at 0x7fa9e0e4c378>
>>> wrapped_object.__eq__
<method-wrapper '__eq__' of structure.WrappedObject object at 0x7fa9e0e4c378>

我需要做什么才能使此类可哈希?

最佳答案

对于内置对象,Python 使用散列 slot ( Python docs link ) 而不是 __hash__() 方法。因此,新的内置对象需要填充哈希槽。这需要一个特定的方法原型(prototype)。

在 WrappedObject C++ 文件中:

long WrappedObject::getHash();

并且在 SWIG 包装器定义文件中:

%rename(__hash__) WrappedObject::getHash;
%feature("python:slot", "tp_hash", functype="hashfunc") WrappedObject::getHash;

这对我有用!

关于python - 在 Python 中使 SWIG 包装内置类 "hashable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28485264/

相关文章:

django - 使用 Django ORM 连接两个表之间的记录

c++ - 客户端主题列表的数据结构

go - 如何将 slice 分配给 HashMap

python - 如何在 pandas 的 DataFrame.plot.hist 中使用不同的轴刻度?

Windows 上的 python joblib Parallel 即使添加了 "if __name__ == ' __main_ _':"也无法正常工作

python - python 函数关心你是否使用它们的输出吗?

python - 如何从孙子类调用 super 方法?

java - 使用 Stream API 获取具有匹配键的映射条目

python - 从 pandas apply 构造一个 DataFrame

python 2.6 : How to access base class descriptor field hidden by derived class?