I am trying to subclass a pandas Series and overload the operators, but cannot figure out why I'm getting a recursion error. Minimally reproduceable example below:
import pandas as pd
class MySeries(pd.Series):
def __mul__(self, other):
print('hello!')
return super().mul(other)
MySeries([1,2,3]) * 1
I get the following error:
hello!
...
hello!
File "/home/jibi/.local/lib/python3.9/site-packages/pandas/core/ops/__init__.py", line 197, in flex_wrapper
return op(self, other)
File "<stdin>", line 4, in __mul__
...
File "/home/jibi/.local/lib/python3.9/site-packages/pandas/core/ops/__init__.py", line 197, in flex_wrapper
return op(self, other)
File "<stdin>", line 4, in __mul__
packages/pandas/core/ops/common.py", line 90, in get_op_result_name
if isinstance(right, (ABCSeries, ABCIndex)):
RecursionError: maximum recursion depth exceeded
Observations:
- the following don't seem to make a difference:
- adding a
mulmethod - adding a
__rmul__method - adding the
_constructormethod (https://pandas.pydata.org/docs/development/extending.html#subclassing-pandas-data-structures)
- adding a
- The error only occurs when I multiply the subclassed instance by an integer, but all is well if I multiply it by a Series or another subclassed instance
- calling
MySeries([1,2,3]).mul(1)also breaks. It doesn't break if I remove the__mul__method inMySeries. - This happens with other operators (
__add__,__sub__, etc) - I can subclass a
DataFrameand override the__mul__method with the exact same code and the*operator behaves as expected (i.e. this is only happening when I subclass aSeries)
Been banging my head on the desk for a few hours now--any insight is appreciated! Thanks!
pandas version 1.4.3; python 3.9.5