def split_unescape(s, delim, escape='\\', unescape=True):
    """
    >>> split_unescape('foo|bar', '|')
    ['foo', 'bar']
    >>> split_unescape(r'foo\\|bar', '|')
    ['foo|bar']
    >>> split_unescape(r'foo\\|bar', '|', unescape=True)
    [r'foo|', 'bar']
    >>> split_unescape(r'foo\\|bar', '|', unescape=False)
    [r'foo\\', 'bar']
    >>> split_unescape(r'foo', '|', unescape=True)
    [r'foo']
    """
    ret = []
    current = []
    itr = iter(s)
    for ch in itr:
        if ch == escape:
            try:
                if not unescape:
                    current.append(escape)
                current.append(next(itr))
            except StopIteration:
                if unescape:
                    current.append(escape)
        elif ch == delim:
            ret.append(''.join(current))
            current = []
        else:
            current.append(ch)
    ret.append(''.join(current))
    return ret
