nbbase.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """Python API for composing notebook elements
  2. The Python representation of a notebook is a nested structure of
  3. dictionary subclasses that support attribute access.
  4. The functions in this module are merely helpers to build the structs
  5. in the right form.
  6. """
  7. # Copyright (c) IPython Development Team.
  8. # Distributed under the terms of the Modified BSD License.
  9. from __future__ import annotations
  10. from nbformat.corpus.words import generate_corpus_id as random_cell_id
  11. from nbformat.notebooknode import NotebookNode
  12. # Change the nbformat_minor and nbformat_schema variables when incrementing the
  13. # nbformat version
  14. # current major version
  15. nbformat = 4
  16. # current minor version
  17. nbformat_minor = 5
  18. # schema files for (major, minor) version tuples. (None, None) means the current version
  19. nbformat_schema = {
  20. (None, None): "nbformat.v4.schema.json",
  21. (4, 0): "nbformat.v4.0.schema.json",
  22. (4, 1): "nbformat.v4.1.schema.json",
  23. (4, 2): "nbformat.v4.2.schema.json",
  24. (4, 3): "nbformat.v4.3.schema.json",
  25. (4, 4): "nbformat.v4.4.schema.json",
  26. (4, 5): "nbformat.v4.5.schema.json",
  27. }
  28. def validate(node, ref=None):
  29. """validate a v4 node"""
  30. from nbformat import validate as validate_orig
  31. return validate_orig(node, ref=ref, version=nbformat)
  32. def new_output(output_type, data=None, **kwargs):
  33. """Create a new output, to go in the ``cell.outputs`` list of a code cell."""
  34. output = NotebookNode(output_type=output_type)
  35. # populate defaults:
  36. if output_type == "stream":
  37. output.name = "stdout"
  38. output.text = ""
  39. elif output_type == "display_data":
  40. output.metadata = NotebookNode()
  41. output.data = NotebookNode()
  42. elif output_type == "execute_result":
  43. output.metadata = NotebookNode()
  44. output.data = NotebookNode()
  45. output.execution_count = None
  46. elif output_type == "error":
  47. output.ename = "NotImplementedError"
  48. output.evalue = ""
  49. output.traceback = []
  50. # load from args:
  51. output.update(kwargs)
  52. if data is not None:
  53. output.data = data
  54. # validate
  55. validate(output, output_type)
  56. return output
  57. def output_from_msg(msg):
  58. """Create a NotebookNode for an output from a kernel's IOPub message.
  59. Returns
  60. -------
  61. NotebookNode: the output as a notebook node.
  62. Raises
  63. ------
  64. ValueError: if the message is not an output message.
  65. """
  66. msg_type = msg["header"]["msg_type"]
  67. content = msg["content"]
  68. if msg_type == "execute_result":
  69. return new_output(
  70. output_type=msg_type,
  71. metadata=content["metadata"],
  72. data=content["data"],
  73. execution_count=content["execution_count"],
  74. )
  75. if msg_type == "stream":
  76. return new_output(
  77. output_type=msg_type,
  78. name=content["name"],
  79. text=content["text"],
  80. )
  81. if msg_type == "display_data":
  82. return new_output(
  83. output_type=msg_type,
  84. metadata=content["metadata"],
  85. data=content["data"],
  86. )
  87. if msg_type == "error":
  88. return new_output(
  89. output_type=msg_type,
  90. ename=content["ename"],
  91. evalue=content["evalue"],
  92. traceback=content["traceback"],
  93. )
  94. raise ValueError("Unrecognized output msg type: %r" % msg_type)
  95. def new_code_cell(source="", **kwargs):
  96. """Create a new code cell"""
  97. cell = NotebookNode(
  98. id=random_cell_id(),
  99. cell_type="code",
  100. metadata=NotebookNode(),
  101. execution_count=None,
  102. source=source,
  103. outputs=[],
  104. )
  105. cell.update(kwargs)
  106. validate(cell, "code_cell")
  107. return cell
  108. def new_markdown_cell(source="", **kwargs):
  109. """Create a new markdown cell"""
  110. cell = NotebookNode(
  111. id=random_cell_id(),
  112. cell_type="markdown",
  113. source=source,
  114. metadata=NotebookNode(),
  115. )
  116. cell.update(kwargs)
  117. validate(cell, "markdown_cell")
  118. return cell
  119. def new_raw_cell(source="", **kwargs):
  120. """Create a new raw cell"""
  121. cell = NotebookNode(
  122. id=random_cell_id(),
  123. cell_type="raw",
  124. source=source,
  125. metadata=NotebookNode(),
  126. )
  127. cell.update(kwargs)
  128. validate(cell, "raw_cell")
  129. return cell
  130. def new_notebook(**kwargs):
  131. """Create a new notebook"""
  132. nb = NotebookNode(
  133. nbformat=nbformat,
  134. nbformat_minor=nbformat_minor,
  135. metadata=NotebookNode(),
  136. cells=[],
  137. )
  138. nb.update(kwargs)
  139. validate(nb)
  140. return nb