Search code examples
joblibpython-attrs

How to customize attrs field hash


I'd like to use a Numpy array as a field value while keeping my attrs class hashable. For that purpose, I found joblib's hash() function to be a good means of hashing Numpy arrays. Is there any possibility to keep using attrs's default hash function while specifying manually how to hash each field, e.g. with something like

import attrs
import numpy as np
from joblib import hash as jbhash

@attrs.frozen
class MyClass:
    field: np.ndarray = attrs.field(hash=jbhash)  # I know this doesn't work at the moment

or do I have to write my own __hash__()?

Notes:

  • I omitted a converter making field non-writeable for brevity)
  • Context: My goal is to use this data class as an argument of a function memoized using functools.lru_cache().

Solution

  • I'm afraid that's currently not possible, primarily because nobody ever asked for it. Hashing is usually something people don't care about until it breaks...

    The feature request is tracked at https://github.com/python-attrs/attrs/issues/1076