import functools


def with_header(header=None):
    """Decorator that adds a section header if there's a any output

    The decorated function should yield output lines; if there are any the
    header gets added.
    """
    def wrap(func):
        @functools.wraps(func)
        def wrapped(cls, remaining_attrs):
            result = list(func(cls, remaining_attrs))
            if result:
                # Sphinx/ReST doesn't allow "-----" just anywhere :(
                yield u''
                yield u'.. raw:: html'
                yield u''
                yield u'    <hr>'
                yield u''
                if header:
                    yield header + u':'
                    yield u''
                for row in result:
                    yield row
        return wrapped
    return wrap