I am making a subclass of a well-established python class:
pendulum.Period, which overrides both
__init__ (it does this because it is subclassing the python builtin class
timedelta, which uses
In my case, I want my class to handle a wider range of arguments than the superclass. The only way I have managed to get the code to work is to duplicate my handling code in both
__init__ -- this is because, per the documentation, the arguments passed to
__new__ are then passed to the
__init__ of the new instance, unaltered.
The result is repeated code execution. Is this avoidable?
from pendulum import Period, Date def _toDate(val): """ Convert various inputs into a Date """ if isinstance(val, int) or isinstance(val, float): return Date.fromtimestamp(val) elif isinstance(val, tuple): return Date(*val) return Date(val.year, val.month, val.day) class MyInterval(Period): def __new__(cls, start, end, inclusive=True, **kwargs): start = _toDate(start) end = _toDate(end) if inclusive: end = end.add(days=1) return super(MyInterval, cls).__new__(cls, start, end, **kwargs) def __init__(self, start, end, inclusive=True, **kwargs): """ Creates a pendulum Period where the interval is limited to whole days. Both are cast to dates, then the end date is incremented by one day if inclusive=True :param start: cast to date :param end: cast to date :param inclusive: [True] whether the last day of the interval should be included (increments by 1 day) """ start = _toDate(start) end = _toDate(end) if inclusive: end = end.add(days=1) super(MyInterval, self).__init__(start, end, **kwargs)