def extract_code(obj, compile_mode):
    """
    Generic function for converting objects into instances of `CodeType`.
    """
    try:
        code = obj.__code__
        if isinstance(code, CodeType):
            return code
        raise ValueError(
            "{obj} has a `__code__` attribute, "
            "but it's an instance of {notcode!r}, not CodeType.".format(
                obj=obj,
                notcode=type(code).__name__,
            )
        )
    except AttributeError:
        raise ValueError("Don't know how to extract code from %s." % obj)