import re


def unindex_0dimensional(text, ydtype):
    """
    If a loop template includes assignments to 0-dimensional return variables
    like 'y[] = ', replace them with return statements (cast to ydtype), after
    removing all existing return statements.

    Examples
    --------

    >>> text = '''\
    ...     if foo:
    ...         PyArray_FillWithScalar(y, NAN)
    ...     y[] = a
    ...     return y
    ...     ''''
    >>> print(unindex_0dimensional(text, 'float64'))
        if foo:
            return np.float64(NAN)
        return np.float64(a)
    """
    if 'y[] = ' in text:
        text = text.replace('return y', '')
        text = re.sub(r'PyArray_FillWithScalar\(y, (\w+)\)',
                      r'return np.%s(\1)' % ydtype, text)
        text = re.sub(r'y\[\] = <np.(\w+)_t> (.+)', r'return np.\1(\2)', text)
        text = re.sub(r'y\[\] = (.+)', r'return np.%s(\1)' % ydtype, text)
    return text