vendredi 23 juillet 2021

Hashable subclasses of mutable classes in Python

I want to build a subclass of a class which is basically a wrapper around a list/dictionary, and I want to use instances of this class as keys. In order to have easy access to the list/dictionary methods, I figured I can just subclass them, but then I lose hashability.

I understand that this is incompatible with the __eq__ of the mutable classes (and I don't need it), so I came up with the following solution.

class Foo(list):
    __hash__ = object.__hash__
    __eq__ = object.__eq__

Though I doubt this will come up in my specific applications, I guess this might cause problems if another class (with its own __hash__) would appear between Foo and list in the MRO of a subclass.

  1. Is there a more Pythonic way of doing this? I could just add a list/dictionary as an attribute and then simply use the attribute (which would make code elsewhere more cumbersome) or the list/dictionary methods I need (but that'd be much more messy if I need more than a couple of methods).
  2. Is there some pattern/recipe that would allow me to do this sort of thing in a cooperative setting (in other words, how should I change the code if I do in fact anticipate another class between Foo and list in MRO)?

Aucun commentaire:

Enregistrer un commentaire