From b385816cf9bb2c036259e31d3d658c9fb41d85da Mon Sep 17 00:00:00 2001 From: Mike Lang Date: Thu, 9 Apr 2015 20:16:14 -0700 Subject: [PATCH] funcutils: Add partial_ordering(), decorator similar to functools.total_ordering() --- boltons/funcutils.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/boltons/funcutils.py b/boltons/funcutils.py index b3a3dfb..965c4b5 100644 --- a/boltons/funcutils.py +++ b/boltons/funcutils.py @@ -98,6 +98,24 @@ def copy_function(orig, copy_dict=True): return ret +def partial_ordering(cls): + """Class decorator. Similar to functools.total_ordering, except it + is used to define partial orderings (ie. it is possible that x is niether + greater than, equal to or less than y). It assumes the presence + of a <= (__le__) and >= (__ge__) method, but nothing else. + It will not override any existing additional comparison methods. + """ + def __lt__(self, other): return self <= other and not self >= other + def __gt__(self, other): return self >= other and not self <= other + def __eq__(self, other): return self >= other and self <= other + + if not hasattr(cls, '__lt__'): cls.__lt__ = __lt__ + if not hasattr(cls, '__gt__'): cls.__gt__ = __gt__ + if not hasattr(cls, '__eq__'): cls.__eq__ = __eq__ + + return cls + + class InstancePartial(functools.partial): """:class:`functools.partial` is a huge convenience for anyone working with Python's great first-class functions. It allows