Skip to content
Snippets Groups Projects
Commit 8c011f88 authored by Daniele Nicolodi's avatar Daniele Nicolodi
Browse files

duration: Fix comparison functions

Using functools.total_ordering does not work when inheriting from
datetime.timedelta because the class appears to already implement all
the comparison methods.

Avoid massive code duplication with clever(?) dynamic function
generation. The same technique could be used to generate methods
implementing binary functions.

Also add a __neg__() implementation.
parent 8b8dacc6
No related branches found
No related tags found
No related merge requests found
import functools
import datetime import datetime
import re import re
...@@ -37,7 +36,6 @@ def strfdelta(td: datetime.timedelta, frmt: str): ...@@ -37,7 +36,6 @@ def strfdelta(td: datetime.timedelta, frmt: str):
return frmt.format_map(values) return frmt.format_map(values)
@functools.total_ordering
class Duration(datetime.timedelta): class Duration(datetime.timedelta):
def __new__(cls, value): def __new__(cls, value):
if isinstance(value, datetime.timedelta): if isinstance(value, datetime.timedelta):
...@@ -65,19 +63,8 @@ class Duration(datetime.timedelta): ...@@ -65,19 +63,8 @@ class Duration(datetime.timedelta):
frmt = '% 03Hh%02M' if self < 0 else '%02Hh%02M' frmt = '% 03Hh%02M' if self < 0 else '%02Hh%02M'
return strfdelta(self, frmt) return strfdelta(self, frmt)
def __eq__(self, other): def __neg__(self):
if isinstance(other, datetime.timedelta): return Duration(-self.total_seconds())
return super().__eq__(other)
if isinstance(other, (int, float)):
return self.total_seconds() == other
return NotImplemented
def __lt__(self, other):
if isinstance(other, datetime.timedelta):
return super().__lt__(other)
if isinstance(other, (int, float)):
return self.total_seconds() < other
return NotImplemented
def __sub__(self, other): def __sub__(self, other):
if isinstance(other, datetime.timedelta): if isinstance(other, datetime.timedelta):
...@@ -96,3 +83,17 @@ class Duration(datetime.timedelta): ...@@ -96,3 +83,17 @@ class Duration(datetime.timedelta):
return NotImplemented return NotImplemented
__radd__ = __add__ __radd__ = __add__
def _cmp_op(op):
def func(self, other):
if isinstance(other, datetime.timedelta):
return getattr(super(Duration), op)(other)
if isinstance(other, (int, float)):
return getattr(self.total_seconds(), op)(other)
return NotImplemented
return func
for op in '__eq__', '__lt__', '__le__', '__gt__', '__ge__':
setattr(Duration, op, _cmp_op(op))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment