nbbase.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 COPYING, distributed as part of this software.
  10. #-----------------------------------------------------------------------------
  11. #-----------------------------------------------------------------------------
  12. # Imports
  13. #-----------------------------------------------------------------------------
  14. import pprint
  15. import uuid
  16. from ipython_genutils.ipstruct import Struct
  17. from ipython_genutils.py3compat import unicode_type
  18. #-----------------------------------------------------------------------------
  19. # Code
  20. #-----------------------------------------------------------------------------
  21. class NotebookNode(Struct):
  22. pass
  23. def from_dict(d):
  24. if isinstance(d, dict):
  25. newd = NotebookNode()
  26. for k,v in d.items():
  27. newd[k] = from_dict(v)
  28. return newd
  29. elif isinstance(d, (tuple, list)):
  30. return [from_dict(i) for i in d]
  31. else:
  32. return d
  33. def new_code_cell(code=None, prompt_number=None):
  34. """Create a new code cell with input and output"""
  35. cell = NotebookNode()
  36. cell.cell_type = u'code'
  37. if code is not None:
  38. cell.code = unicode_type(code)
  39. if prompt_number is not None:
  40. cell.prompt_number = int(prompt_number)
  41. return cell
  42. def new_text_cell(text=None):
  43. """Create a new text cell."""
  44. cell = NotebookNode()
  45. if text is not None:
  46. cell.text = unicode_type(text)
  47. cell.cell_type = u'text'
  48. return cell
  49. def new_notebook(cells=None):
  50. """Create a notebook by name, id and a list of worksheets."""
  51. nb = NotebookNode()
  52. if cells is not None:
  53. nb.cells = cells
  54. else:
  55. nb.cells = []
  56. return nb