How to Skip Cell Execution in Jupyter Notebook

In this article, I’ll show you how to skip the execution of cells in Jupyter Notebook based on certain conditions.
The methods described here are applicable to Google Colaboratory and Kaggle Notebooks.

To skip cell execution, create a custom magic command as follows:

  1. First, create a skip magic command that does nothing.

    from IPython.core.magic import register_cell_magic
    
    @register_cell_magic
    def skip(line, cell):
        return
    
  2. To skip a cell, simply add %%skip at the top line of the cell.

    %%skip
    <code>
    

Next, let’s explore how to skip cell execution based on a condition.

  1. Create a skip_if magic command.

    from IPython.core.magic import register_cell_magic
    from IPython import get_ipython
    
    @register_cell_magic
    def skip_if(line, cell):
        if eval(line):
            return
        get_ipython().run_cell(cell)
    
  2. To use it, add %%skip_if <condition> at the top of the cell.

    %%skip_if <condition>
    <code>
    

Finally, I will explain how to skip all subsequent cells based on a condition.

  1. Modify the run_cell function as follows:

    from IPython import get_ipython
    
    SKIP_CONDITION = <condition>
    
    # Save the original run_cell
    run_cell_org = get_ipython().run_cell
    
    # Create a custom run_cell that skips execution based on the condition
    def custom_run_cell(*args, **kwargs):
        if SKIP_CONDITION:
            if 'raw_cell' in kwargs:
                kwargs['raw_cell'] = ""
            else:
                args = list(args)
                args[0] = ""
                args = tuple(args)
        return run_cell_org(*args, **kwargs)
    
    # Replace the original run_cell
    get_ipython().run_cell = custom_run_cell
    
  2. All subsequent cells will be skipped if the <condition> is true.

Related Content