In PyO3 we're haven't implemented the Hash
trait for the main Python object type (PyAny
) because we're not able to guarantee __hash__
implementations written in Python will not error. (The return value of PyAny::hash
is Result<isize, PyErr>
).
Has anyone else come across problems like this in the past, and do you think it warrants a solution in std
? It's unfortunate that it means Python objects cannot be used with Rust's collections like HashSet
and HashMap
. On the other hand, Hash
being infallible is hugely convenient the vast majority of the time. I'm also not aware of any modification which could be made to the Hash
trait backwards-compatibly to resolve this, and it feels like I'm staring at an edge case here.
The best solution I can think of that doesn't require support in std
is just to panic in the Hash
implementation. PyO3 already uses catch_unwind
at the FFI boundary to prevent Rust panics propagating into C; it wouldn't be hard to transform panics originating from Hash
back into Python exceptions. This just feels a little... dirty, as I understood idiomatic use of panics discourages them from being used for regular error control flow!