pythonjupyter-notebookjupyter-tags

Multiple versions of single Jupyter Notebook for different audiences (e.g. tutors/students) using tags


I'm working on creating assignments for students using Jupyter Notebooks. My goal is to generate different versions of the same Notebook to distribute to tutors and students.

I need certain cells, such as those containing exercise solutions, to be included only in the tutor's version, while other cells should be exclusive to the student's version. Sometimes, I want to remove entire cells, and other times, just the output.

I believe this can be achieved by tagging cells and using nbconvert to save the Notebook (.ipynb) into another .ipynb file.

A similar method was suggested for converting .ipynb to HTML here. I'm interested in hearing if anyone has experience, or creative new ideas, in creating different versions of a single Jupyter Notebook for various audiences.

My project is quite extensive, so I need an automated solution. While I could manually create different versions by copying and pasting if I only had a few Notebooks, this approach isn’t feasible for a larger scale.

Following initial comments, I tried assigning the tag "remove_cell" to some of the Notebook cells (example notebook here) and then removing them using the suggestion of this answer

jupyter nbconvert nbconvert-example.ipynb --TagRemovePreprocessor.remove_cell_tags='{"remove_cell"}'

However, the tagged cells are not removed when saving to Jupyter Notebook with the --to notebook option. They are only removed with the --to html option.


Solution

  • This is all built in to nbconvert. You can just do:

    # ensure all output has been produced
    jupyter nbconvert tutor-source-only.ipynb
        --to notebook \
        --execute
        --output tutor-with-output.ipynb
    
    # remove cells that you want the students to figure out on their own and
    # optionally remove the output of some/all cells, so the students have to 
    # run the notebook 
    jupyter nbconvert tutor-with-output.ipynb \
        --to notebook \
        --output student.ipynb \
        --TagRemovePreprocessor.enabled True \
        --TagRemovePreprocessor.remove_cell_tags remove_cell \
        --TagRemovePreprocessor.remove_all_outputs_tags remove_output
    

    I would advise against using TagRemovePreprocessor.remove_input_tags as the source is kept in the file, but the GUI is told not to show it.

    For any cells where you want to show the students what the output should look like, but not how to produce it, I would recommend writing your own preprocessor that takes the cell, strips the input, and converts the cell to a markdown cell, copying across the output. That way the "output" remains when the students run the notebook.

    You can find more on how to add and run your own preprocessors here: https://nbconvert.readthedocs.io/en/latest/nbconvert_library.html#Custom-Preprocessors