1

In my experiment, I have an instance of a numpy object whose __hash__ method I need to set.

I have tried various approaches (that seem to actually be the very same):

import numpy as np
x = np.array([1, 2, 3])
x.flags.writeable = False  # set the array immutable

setattr(x, '__hash__', lambda self: 0)  # doesn't work without self either
AttributeError: 'numpy.ndarray' object attribute '__hash__' is read-only

x.__hash__ = lambda self: 0
AttributeError: 'numpy.ndarray' object attribute '__hash__' is read-only

Is there any way of forcing the object to accept my implementation? This is actually a broader question: is there a way of assigning any property/method to an existing object (including magic methods etc)?

petrbel
  • 2,428
  • 5
  • 29
  • 49
  • Why do you need to monkey patch the hash method? – jonrsharpe Oct 21 '19 at 17:21
  • Long story short, numpy arrays don't support hashing and it would really help me. It's a complicated situation, though. Also, I'm pretty curious what python can and cannot do to its (already existing) objects :) – petrbel Oct 21 '19 at 17:25
  • 1
    The don't implement a hash because they're *mutable*, see e.g. https://stackoverflow.com/q/31340756/3001761 for some context. – jonrsharpe Oct 21 '19 at 17:28
  • That's right! I forgot to mention setting the array immutable (see https://stackoverflow.com/questions/5541324/immutable-numpy-array).. will edit my original question. – petrbel Oct 21 '19 at 19:49

1 Answers1

0

Create an object class that inherits np? Then write your __hash__ function I'm a bit of a noob, but think this would work?


class Test(np):

    def __hash__(self):
      # function

  • yeah sure that would definitely work at the class-level... however, I am specificaly interested in already existing instances (not classes) – petrbel Oct 21 '19 at 19:50