[Python-3000] ABC for Inequalities
Guido van Rossum
guido at python.org
Tue Feb 12 02:02:27 CET 2008
On Feb 11, 2008 4:43 PM, Raymond Hettinger <python at rcn.com> wrote:
> Was some thought given to providing a mixin for boolean inequalities in total orderings (define __le__ and get the rest for free)?
I think it was briefly mentioned but we didn't get beyond the stage of
"you can do this with a tiny metaclass". There should be a way to
avoid getting the rest for free too though, as the example of sets
shows. There was also the issue of what to do if a subclass defines
only __le__ and a superclass already defined all 6 operators. And
there's also the issue that because of the way it's mapped to a single
tp_richcompare slot in C, 'object' defines all 6 operators, but 4 of
these raise exceptions. IOW it's messy.
> One of the motivating examples in the ABC pep was that the presence of __getitem__ was insufficient to distinguish between a sequence and a mapping. By registering one of the collections ABCs, a class can make an affirmative declaration that it is either a mapping or a sequence.
>
> It seems that there is a similar issue with inequalities. If something defines __le__, you don't necessarily know whether it returns a boolean (it could return an array of bools for a vector comparison). Even if a bool is returned, it is not clear whether it implies sortable ordering or whether is something with a completely different meaning (i.e. set.issubset).
I'm not sure I follow the connection with the above query, but I
believe that for now the best approach here is to document the
requirements for the comparisons. E.g. for Real numbers we require a
total ordering based on the standard ordering for mathematical reals
(insofar as practical in the light of inexactness and NaNs, of
course), for Sequences I believe we specify that it should order
item-wise, and for Sets we redefine the comparisons as set inclusion
operators.
A class whose __le__ returns an array or results should probably not
derive directly from one of those standard ABCs. (Possibly the numpy
folks might be interested in defining a different ABC for arrays whose
'+' operator does elementwise addition instead of concatenation; but
that's up to them.)
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-3000
mailing list