nbbase.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """The basic dict based notebook format.
  2. Authors:
  3. * Brian Granger
  4. """
  5. # -----------------------------------------------------------------------------
  6. # Copyright (C) 2008-2011 The IPython Development Team
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file LICENSE, distributed as part of this software.
  10. # -----------------------------------------------------------------------------
  11. # -----------------------------------------------------------------------------
  12. # Imports
  13. # -----------------------------------------------------------------------------
  14. from __future__ import annotations
  15. from nbformat._struct import Struct
  16. # -----------------------------------------------------------------------------
  17. # Code
  18. # -----------------------------------------------------------------------------
  19. class NotebookNode(Struct):
  20. """A notebook node object."""
  21. def from_dict(d):
  22. """Create notebook node(s) from an object."""
  23. if isinstance(d, dict):
  24. newd = NotebookNode()
  25. for k, v in d.items():
  26. newd[k] = from_dict(v)
  27. return newd
  28. if isinstance(d, (tuple, list)):
  29. return [from_dict(i) for i in d]
  30. return d
  31. def new_code_cell(code=None, prompt_number=None):
  32. """Create a new code cell with input and output"""
  33. cell = NotebookNode()
  34. cell.cell_type = "code"
  35. if code is not None:
  36. cell.code = str(code)
  37. if prompt_number is not None:
  38. cell.prompt_number = int(prompt_number)
  39. return cell
  40. def new_text_cell(text=None):
  41. """Create a new text cell."""
  42. cell = NotebookNode()
  43. if text is not None:
  44. cell.text = str(text)
  45. cell.cell_type = "text"
  46. return cell
  47. def new_notebook(cells=None):
  48. """Create a notebook by name, id and a list of worksheets."""
  49. nb = NotebookNode()
  50. if cells is not None:
  51. nb.cells = cells
  52. else:
  53. nb.cells = []
  54. return nb