bisect uses __cmp__()?
Tim Peters
tim.one at comcast.net
Tue Jul 29 18:06:47 EDT 2003
[Gary Robinson]
> I'm wondering if bisect.insort is guaranteed to use a __cmp__ method,
> for now and for future python versions, if it exists, for the items
> being inserted?
Well, it doesn't use __cmp__ directly now, and never has: it uses Python's
infix "<" operator. While not documented, it's deliberate that bisect
*only* uses "<", so that instances of a class implementing only __lt__ can
use bisect. This is the same (also undocumented) rule used in CPython's
list.sort() implementation. Similarly, list.index(object) uses only "==",
so that instances of classes defining only __cmp__ or only __eq__ work fine.
Ditto for dict key lookups.
> That would be good to know because then you don't have to define
> __lt__ etc. if all you care about is being able to use bisect.insort.
Or, it so happens, you can define only __lt__, and skip defining __cmp__
etc. Defining only __cmp__ works too.
> If true, I suggest that it might be good to mention the bisect
> library docs. In any case, if there is a clear answer to my question
> I'd appreciate knowing what it is...
You never have to define __lt__ (to use bisect or anything else in the core
distribution). There may be a good performance to reason to define __lt__
instead of __cmp__, though, if some type can implement __lt__ more
efficiently than it can implement __cmp__. I think that's rare. More
common is that __eq__/__ne__ can be implemented more efficiently.
More information about the Python-list
mailing list