Python 3.0 - is this true?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Nov 11 02:10:00 CET 2008


On Mon, 10 Nov 2008 12:51:51 +0000, Duncan Grisby wrote:

> I have an object database written in Python. It, like Python, is
> dynamically typed. It heavily relies on being able to sort lists where
> some of the members are None. To some extent, it also sorts lists of
> other mixed types. It will be very hard to migrate this aspect of it to
> Python 3.

No, it is "very hard" to sort *arbitrary* objects consistently. If it 
appears to work in Python 2.x that's because you've been lucky to never 
need to sort objects that cause it to break. 

But if you have a list consisting of only a few types, then it is not 
that hard to come up with a strategy for sorting them. All you need is a 
key function. Suppose that you want to sort a list of numbers and None. 
Then this should do what you expect:

# untested
alist.sort(key=lambda x: (0, -99) if x is None else (1, x))


Another suggestion would be a key function that wraps the objects in a 
"compare anything" proxy class. This is very hard to get right for 
arbitrary types, which is why sorting in Python 2.x apparently contains 
subtle bugs. But if you control the types that can appear in your list, 
it's much simpler. I leave the full details as an exercise, but the heart 
of it will be something like this:

class SortableProxy(object):
    # define the order of types
    types = [NoneType, str, int, MyWackyObjectClass]
    def __lt__(self, other):
        if type(self.proxy) == type(other.proxy):
             return self.proxy < other.proxy
        p = self.types.index(type(self.proxy)
        q = self.types.index(type(other.proxy)
        return p < q

I leave it to you to sort out the remaining details (pun intended).



-- 
Steven



More information about the Python-list mailing list