import operator


def sort_posts(posts, *keys):
    """Sort posts by a given predicate. Helper function for templates.

    If a key starts with '-', it is sorted in descending order.

    Usage examples::

        sort_posts(timeline, 'title', 'date')
        sort_posts(timeline, 'author', '-section_name')
    """
    # We reverse the keys to get the usual ordering method: the first key
    # provided is the most important sorting predicate (first by 'title', then
    # by 'date' in the first example)
    for key in reversed(keys):
        if key.startswith('-'):
            key = key[1:]
            reverse = True
        else:
            reverse = False
        try:
            # An attribute (or method) of the Post object
            a = getattr(posts[0], key)
            if callable(a):
                keyfunc = operator.methodcaller(key)
            else:
                keyfunc = operator.attrgetter(key)
        except AttributeError:
            # Post metadata
            keyfunc = operator.methodcaller('meta', key)

        posts = sorted(posts, reverse=reverse, key=keyfunc)
    return posts