I have a small helper class:
class AnyOf(object): def __init__(self, *args): self.elements = args def __eq__(self, other): return other in self.elements
This allows me to do sweet magic like:
>>> arr = np.array([1,2,3,4,5]) >>> arr == AnyOf(2,3) np.array([False, True, True, False, False])
without using list comprehension (as in np.array(x in (2,3) for x in arr ).
(I support a user interface that allows (trusted) users to enter arbitrary code, and a == AnyOf(1,2,3) much more enjoyable than list comprehension for a non-technical user.)
But!
It only works in one direction! For example, if I were to do AnyOf(2,3) == arr , then the AnyOf class __eq__ would never be called: instead, the NumPy array __eq__ method is __eq__ , which inside (I would assume) calls the __eq__ method of all its elements.
This made me wonder: why doesn't Python allow the right- __eq__ equivalent of __eq__ ? (Roughly equivalent to methods like __radd__ , __rmul__ , etc.)