On Dec 14, 11:04 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > 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.
I wasn't going to raise the exception, I was thinking about calling a function that raised the exception. Assume for a moment that list's __le__ were implemented as above. class BadGT(object): def __gt__(self, o): raise RuntimeError("I just hate this operation") def __le__(self, o): return id(self) <= id(other) >>> x = [BadGT(), BadGT()] >>> x <= [] If lists implementation of __le__ calls __gt__ on its constituents *then* it'll be a RuntimeError. I've tested list, and it safely compares lists containing BadGT objects, as along I don't call __gt__ myself. So I was contemplating implementing a phalanx of tests along these lines, which the current version of my container will surely fail. > BTW, what is a LarchTree? Googling just brings up the actual botanical > tree, a type of conifer. > > http://en.wikipedia.org/wiki/Larch It was a Monty Python reference. I'm actually still fiddling around with a doubly-linked list implementation. It's kinda embarrassing so I hid that fact, but actually I'm learning a bunch of Python and getting design practice from this exercise (it turns out linked lists have keys!). -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list