def write_python_doc(fh, metadata, defblocks, block):
    """Writes a representation of a compiled template--its metadata, defined
    blocks, and primary block--to the given file handle.
    """
    fh.write('# Compiled template generated by the Template Toolkit\n\n')
    fh.write('metadata = %r\n\n' % metadata)
    fh.write('blocks = {}\n\n')
    for name, code in sorted(defblocks.items()):
        fh.write(code)
        fh.write('\nblocks[%r] = block\n\n' % name)
    fh.write(block)
    fh.write(
        "\ndocument = Document({'METADATA': metadata, 'DEFBLOCKS': blocks, 'BLOCK': block})\n"
        )
