import re


def _split_code_into_blocks(code):
    """Split a string of Python code into the top level
    code blocks.
    Assumes there are no multi-line expressions
    """
    blocks = []
    code_lines = code.splitlines()
    # remove empty lines
    code_lines = [line for line in code_lines if len(line.strip())]
    block = None
    for line in code_lines:
        if block is None:
            block = line + '\n'
        elif (len(line) - len(line.lstrip()) > 0
                or re.match(r'^elif', line)
                or re.match(r'^else:', line)
                or re.match(r'^except', line)
                or re.match(r'^finally', line)):
            block += line + '\n'
        elif len(line) - len(line.lstrip()) == 0:
            blocks.append(block)
            block = line + '\n'
    if block is not None:
        blocks.append(block)
    # remove last new line character
    blocks = [b.strip() for b in blocks]
    return blocks