
_pattern_type = type(sre_compile.compile("", 0))

@functools.lru_cache(maxsize=500, typed=True)
def _compile(pattern, flags):
    # internal: compile pattern
    if isinstance(pattern, _pattern_type):
        if flags:
            raise ValueError(
                "Cannot process flags argument with a compiled pattern")
        return pattern
    if not sre_compile.isstring(pattern):
        raise TypeError("first argument must be string or compiled pattern")
    return sre_compile.compile(pattern, flags)