防止可变类的自动哈希功能 [英] Prevent automatic hash function for mutable classes

查看:51
本文介绍了防止可变类的自动哈希功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python仅允许对不可变对象使用哈希值.例如,

Python allows hash values only for immutable objects. For example,

hash((1,2,3))

可以,但是

hash([1,2,3])

引发TypeError: unhashable type: 'list'.请参见 Python文档.但是,当我通过通常的boost::python::class_<>函数在Boost.Python中包装一个C ++类时,每个生成的Python类都有一个默认的哈希函数,该哈希值与对象在内存中的位置有关. (在我的64位操作系统上,哈希值是位置除以8.)

raises a TypeError: unhashable type: 'list'. See the Python documentation. However, when I wrap a C++ class in Boost.Python via the usual boost::python::class_<> function, every generated Python class has a default hash function, where the hash value is related to the object's location in memory. (On my 64-bit OS, the hash value is the location divided by 8.)

当我向Python公开一个可以更改其成员的类(任何可变数据结构,所以这是非常普遍的情况!)时,我不需要默认的哈希函数,但想要调用hash()会引发相同的结果TypeError,因为用户收到Python自己的可变数据类型.特别是,用户不应意外地将可变对象用作字典键.如何在C ++代码中实现这一目标?

When I expose a class to Python whose members can be changed (any mutable data structure, so this is a very common situation!), I do not want a default hash function but want a call to hash() raise the same TypeError as users receive for Python's own mutable data types. In particular, users shouldn't be able to accidentally use mutable objects as dictionary keys. How can I achieve this in the C++ code?

推荐答案

我发现它的运行方式:

boost::python::class_<MyClass>("MyClass")
  .setattr("__hash__", boost::python::object());

没有参数初始化的boost::python::object对应于None.如

A boost::python::object which is initialized with no arguments corresponds to None. The procedure for disabling hash generation in the pure Python C API is a little more complicated, as is described in the Python documentation. However, the above code snippet apparently does the job in boost::python.

这篇关于防止可变类的自动哈希功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆