import pickle


def load_api(api_path, check_readiness=True):
    """Load a GridAPI instance, possibly waiting until it becomes ready.

    Parameters
    ----------
        api_path : path_line
            Path where the instance is pickled.

        check_readiness : bool (optional, default True)
            Whether to check if the GridAPI instance is ready.

    Returns
    -------
        api : GridAPI
            GridAPI instance such that api.ready() is True.

    """
    while True:
        try:
            with open(api_path, 'rb') as api_file:
                api = pickle.load(api_file)
            if not check_readiness or api.ready():
                break
        except:
            continue

    return api