def fold(header):
    """Fold a header line into multiple crlf-separated lines at column 72.

    >>> fold(b'foo')
    'foo'
    >>> fold(b'foo  '+b'foo'*24).splitlines()[0]
    'foo  '
    >>> fold(b'foo'*25).splitlines()[-1]
    ' foo'
    >>> len(fold(b'foo'*25).splitlines()[0])
    72
    """
    i = header.rfind(b"\r\n ")
    if i == -1:
        pre = b""
    else:
        i += 3
        pre = header[:i]
        header = header[i:]
    while len(header) > 72:
        i = header[:72].rfind(b" ")
        if i == -1:
            j = 72
        else:
            j = i + 1
        pre += header[:j] + b"\r\n "
        header = header[j:]
    return pre + header
Fold a header line into multiple crlf-separated lines at column 72.

    >>> fold(b'foo')
    'foo'
    >>> fold(b'foo  '+b'foo'*24).splitlines()[0]
    'foo  '
    >>> fold(b'foo'*25).splitlines()[-1]
    ' foo'
    >>> len(fold(b'foo'*25).splitlines()[0])
    72
    
python/dkim/__init__.py