container.___le___ can use only <=?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Dec 14 23:04:31 EST 2007


On Fri, 14 Dec 2007 21:15:44 +0000, Neil Cerutti wrote:

> When implementing the rich comparison operators for some sort of
> container, it's tempting to save code by doing something like:
> 
>  class LarchTree:
>    ...
>    def __gt__(self, other):
>      # A lot of code to traverse the tree
>    def __le__(self):
>      return not self > other
> 
> However, if I'm thinking correctly, this is a bad idea. The reasoning
> being that > and <= are not required to be each others opposite for
> arbitrary value types, and may not even both be supplied by the
> contained objects.
> 
> If a LarchTree user stores objects that don't support __gt__, will he
> have a legitimate complaint when using LarchTree.__le__ results in an
> attribute error?

I'm not sure that an AttributeError is the right exception to raise, but 
in general I'd say that if the contained objects don't support "normal" 
comparisons (that is, if < and >= aren't opposites, etc.) then all bets 
are off. "Behaviour is undefined" time.

BTW, what is a LarchTree? Googling just brings up the actual botanical 
tree, a type of conifer.

http://en.wikipedia.org/wiki/Larch


If you haven't already done so, you should consider emulating the 
behaviour of lists, and only raise an error if it is absolutely necessary:

>>> L1 = [35, 23+42j]
>>> L2 = [37, 18]
>>> L1 <= L2
True
>>> L1 = [23+42j, 35]
>>> L1 <= L2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: no ordering relation is defined for complex numbers





-- 
Steven



More information about the Python-list mailing list