import importlib
import warnings


def import_or_raise(library, error_msg=None, warning=False):
    """Attempts to import the requested library by name. If the import fails, raises an ImportError or warning.

    Args:
        library (str): The name of the library.
        error_msg (str): Rrror message to return if the import fails.
        warning (bool): If True, import_or_raise gives a warning instead of ImportError. Defaults to False.

    Returns:
        Returns the library if importing succeeded.

    Raises:
        ImportError: If attempting to import the library fails because the library is not installed.
        Exception: If importing the library fails.
    """
    try:
        return importlib.import_module(library)
    except ImportError:
        if error_msg is None:
            error_msg = ""
        msg = f"Missing optional dependency '{library}'. Please use pip to install {library}. {error_msg}"
        if warning:
            warnings.warn(msg)
        else:
            raise ImportError(msg)
    except Exception as ex:
        msg = f"An exception occurred while trying to import `{library}`: {str(ex)}"
        if warning:
            warnings.warn(msg)
        else:
            raise Exception(msg)