markwalker_
markwalker_

Reputation: 12859

Sorted key returning NoneType comparison TypeError

I'm trying to sort a list made up of objects and lists of (the same type of) objects during a unittest setup, but I'm getting a TypeError: can't compare datetime.date to NoneType.

I know it's incredibly simple, but what am I missing!?

objs = [myobject, myobject]
more_objs = [[myobject, myobject], [myobject, myobject]]

def sort_all_objs(data):
    """
    Sort mixed list by the dates.
    """
    if isinstance(data, list):
        sort_all_objs(data[0])
    else:
        date = getattr(data.calculation, 'duedate')
        if date:
            return date
        raise AttributeError("List doesn't have objects with a duedate attribute: {0}".format(data.calculation))


all_objs = objs + more_objs 
all_objs = sorted(self.all_objs, key=sort_all_objs) 

Upvotes: 0

Views: 162

Answers (1)

Matthew Trevor
Matthew Trevor

Reputation: 14961

In your sort_all_objs function:

if isinstance(data, list): 
    sort_all_objs(data[0]) # recursively call the function
    # no return here
else:
    # else branch returns a date object

The function itself has no return value given so None is returned for sublists.

You might instead want:

    return sort_all_objs(data[0])

Upvotes: 1

Related Questions