import re


def parse_vartype(string):
    """
    >>> parse_vartype("real(dp), dimension(31)")
    ('real', 'dp', 31)
    >>> parse_vartype("real (kind=8)")
    ('real', 'kind=8', None)
    >>> parse_vartype("real")
    ('real', None, None)
    >>> parse_vartype("real, dimension(3)")
    ('real', None, 3)
    """
    # left-hand side of "::"
    type_re = "(?P<dtype>\w+)(\((?P<attrs>.*?)\))*(,dimension\((?P<size>.+?)\))*"
    m = re.search(type_re, string.replace("double precision","real(8)").replace(" ",""))
    if m is None:
        raise ValueError("Failed to parse var type : "+string)
    d = m.groupdict()
    if d["size"] is None:
        size = None
    else:
        size = int(d["size"])
    return d["dtype"], d["attrs"], size