Mike
Mike

Reputation: 71

bisect and lists of user defined objects (python 3)

Before python 3, I used bisect to insert user-defined objects into a list. bisect was happy with this because my user-defined object had a def __cmp__ that defined how to compare the objects. I've read the rationale for not supporting cmp in python 3 and I'm fine with that. I thought a fix for my old code would be to 'decorate' my user-defined object by turning it into a tuple

(integer, user-defined object).

However, if I have a list of my tuples, and try ...

i = bisect_left([list_of_tuples], (integer, user-defined object))

then I get an error "builtins.TypeError: unorderable types ..."

So, (in python 3) how do I use bisect for lists of items that aren't made entirely of things with a natural sort order?

Upvotes: 2

Views: 1925

Answers (1)

novalis
novalis

Reputation: 1142

You need to add an __lt__ method; this is now what is used for comparisons instead of __cmp__

Upvotes: 18

Related Questions