how to get jupyter notebook cells by tag?

867 views
Skip to first unread message

Krishna Bhogaonker

unread,
Jun 8, 2018, 12:52:11 PM6/8/18
to Project Jupyter
Hello folks. So I have created tags for certain notebook cells in a standard Jupyter 6.2.1 notebook. Then I have a widget button, which when pushed will only execute cells with a certain tag. I want to run these cells in python, since the widgets themselves are just standard python notebook widgets. 

I have been looking through posts and github issues, etc., to see if there is a way to extract cell indices by tag, but have not found any documentation on this. Seems like there are some references to a "Jupyter.notebook.get_selected_cells()" function and a "Jupyter.notebook.get_cells()" function, but I have not found any documentation on either of these functions. Of course I might be looking
in the wrong place, etc.

Can anyone tell me what the function is to get all cells with a certain tag, or to lookup cells by text within the cell, etc. Even a link to the documentation would help.

Travis DePrato

unread,
Jun 9, 2018, 5:17:05 PM6/9/18
to jup...@googlegroups.com
In JavaScript (assuming the classic notebook, rather than JupyterLab), you could do this:
function findCellsByTag(tagName) {
  return Jupyter.notebook.get_cells().filter(function(cell) {
    // check that tags is defined and contains desired tag
    return cell.metadata.tags && cell.metadata.tags.includes(tagName)
  });
}
or, with more concise arrow and object destructuring syntax,
function findCellsByTag(tagName) {
  return Jupyter.notebook.get_cells().filter(
    ({metadata: {tags}}) => tags && tags.includes(tagName)
  );
}
To find indices:
function findCellIndicesByTag(tagName) {
  return (Jupyter.notebook.get_cells()
    .filter(
      ({metadata: {tags}}) => tags && tags.includes(tagName)
    )
    .map((cell) => Jupyter.notebook.find_cell_index(cell))
  );
}
--
You received this message because you are subscribed to the Google Groups "Project Jupyter" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jupyter+u...@googlegroups.com.
To post to this group, send email to jup...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jupyter/141830a4-d994-4f30-b275-809bbdb24eda%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Travis DePrato (he/him/his, they/them/theirs)
University of Michigan, Ann Arbor
Computer Science & Engineering
Mathematics (Discrete and Algorithmic Methods)
Reply all
Reply to author
Forward
0 new messages