I am writing a test utility to make assertions with pandas Series easier. For example I would like to be able to write assert my_series == Constant(3)
to check that all the elements of the Series are equal to 3. To do so I have created a class Constant
redefining the comparison operators :
import pandas as pd
class Constant:
def __init__(self, value):
self._value = value
def __eq__(self, other: pd.Series):
return (other == self._value).all()
But depending on the operand order, my comparison implementation is not always used by Python :
s = pd.Series([3]*10)
print("Constant(3) == s :")
print(Constant(3) == s) # GOOD : Constant.__eq__ is called
print("s == Constant(3)")
print(s == Constant(3)) # BAD : Series.__eq__ is called
According to this answer I could solve this by defining Constant
as a subclass of Series
. But if I want Constant
to work with several array-like types I have to make it inheriting from Series
, DataFrame
, ndarray
etc... It would make a very strange object with a lot of useless attributes and methods.
What is the best solution ? For example, is there a way to add several array-like types as base classes of Constant
and then remove all the inherited elements ?