Is there a better way than lambda to filter on attributes/methods of objects? Is there a better (more pythonic?) way to filter a list on attributes or methods of objects than relying on lamda functions?

contexts_to_display = ...
tasks = Task.objects.all()
tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)
tasks = filter(lambda t: not t.is_future(), tasks)
tasks = sorted(tasks, Task.compare_by_due_date)


Here, matches_contexts and is_future are methods of Task.  Should I make those free-functions to be able to use filter(is_future, tasks)?

Any other comment?
I would use a list comprehension:

contexts_to_display = ...
tasks = [t for t in Task.objects.all()
         if t.matches_contexts(contexts_to_display)
         if not t.is_future()]
tasks.sort(cmp=Task.compare_by_due_date)


Since you already have a list, I see no reason not to sort it directly, and that simplifies the code a bit.

The cmp keyword parameter is more of a reminder that this is 2.x code and will need to be changed to use a key in 3.x (but you can start using a key now, too):

import operator
tasks.sort(key=operator.attrgetter("due_date"))
# or
tasks.sort(key=lambda t: t.due_date)


You can combine the comprehension and sort, but this is probably less readable:

tasks = sorted((t for t in Task.objects.all()
                if t.matches_contexts(contexts_to_display)
                if not t.is_future()),
               cmp=Task.compare_by_due_date)