displaypub.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. """An interface for publishing rich data to frontends.
  2. There are two components of the display system:
  3. * Display formatters, which take a Python object and compute the
  4. representation of the object in various formats (text, HTML, SVG, etc.).
  5. * The display publisher that is used to send the representation data to the
  6. various frontends.
  7. This module defines the logic display publishing. The display publisher uses
  8. the ``display_data`` message type that is defined in the IPython messaging
  9. spec.
  10. """
  11. # Copyright (c) IPython Development Team.
  12. # Distributed under the terms of the Modified BSD License.
  13. import sys
  14. from traitlets.config.configurable import Configurable
  15. from traitlets import List
  16. # This used to be defined here - it is imported for backwards compatibility
  17. from .display_functions import publish_display_data
  18. from .history import HistoryOutput
  19. import typing as t
  20. # -----------------------------------------------------------------------------
  21. # Main payload class
  22. # -----------------------------------------------------------------------------
  23. _sentinel = object()
  24. class DisplayPublisher(Configurable):
  25. """A traited class that publishes display data to frontends.
  26. Instances of this class are created by the main IPython object and should
  27. be accessed there.
  28. """
  29. def __init__(self, shell=None, *args, **kwargs):
  30. self.shell = shell
  31. self._is_publishing = False
  32. self._in_post_execute = False
  33. if self.shell:
  34. self._setup_execution_tracking()
  35. super().__init__(*args, **kwargs)
  36. def _validate_data(self, data, metadata=None):
  37. """Validate the display data.
  38. Parameters
  39. ----------
  40. data : dict
  41. The formata data dictionary.
  42. metadata : dict
  43. Any metadata for the data.
  44. """
  45. if not isinstance(data, dict):
  46. raise TypeError("data must be a dict, got: %r" % data)
  47. if metadata is not None:
  48. if not isinstance(metadata, dict):
  49. raise TypeError("metadata must be a dict, got: %r" % data)
  50. def _setup_execution_tracking(self):
  51. """Set up hooks to track execution state"""
  52. self.shell.events.register("post_execute", self._on_post_execute)
  53. self.shell.events.register("pre_execute", self._on_pre_execute)
  54. def _on_post_execute(self):
  55. """Called at start of post_execute phase"""
  56. self._in_post_execute = True
  57. def _on_pre_execute(self):
  58. """Called at start of pre_execute phase"""
  59. self._in_post_execute = False
  60. # use * to indicate transient, update are keyword-only
  61. def publish(
  62. self,
  63. data,
  64. metadata=None,
  65. source=_sentinel,
  66. *,
  67. transient=None,
  68. update=False,
  69. **kwargs,
  70. ) -> None:
  71. """Publish data and metadata to all frontends.
  72. See the ``display_data`` message in the messaging documentation for
  73. more details about this message type.
  74. The following MIME types are currently implemented:
  75. * text/plain
  76. * text/html
  77. * text/markdown
  78. * text/latex
  79. * application/json
  80. * application/javascript
  81. * image/png
  82. * image/jpeg
  83. * image/svg+xml
  84. Parameters
  85. ----------
  86. data : dict
  87. A dictionary having keys that are valid MIME types (like
  88. 'text/plain' or 'image/svg+xml') and values that are the data for
  89. that MIME type. The data itself must be a JSON'able data
  90. structure. Minimally all data should have the 'text/plain' data,
  91. which can be displayed by all frontends. If more than the plain
  92. text is given, it is up to the frontend to decide which
  93. representation to use.
  94. metadata : dict
  95. A dictionary for metadata related to the data. This can contain
  96. arbitrary key, value pairs that frontends can use to interpret
  97. the data. Metadata specific to each mime-type can be specified
  98. in the metadata dict with the same mime-type keys as
  99. the data itself.
  100. source : str, deprecated
  101. Unused.
  102. transient : dict, keyword-only
  103. A dictionary for transient data.
  104. Data in this dictionary should not be persisted as part of saving this output.
  105. Examples include 'display_id'.
  106. update : bool, keyword-only, default: False
  107. If True, only update existing outputs with the same display_id,
  108. rather than creating a new output.
  109. """
  110. if source is not _sentinel:
  111. import warnings
  112. warnings.warn(
  113. "The 'source' parameter is deprecated since IPython 3.0 and will be ignored "
  114. "(this warning is present since 9.0). `source` parameter will be removed in the future.",
  115. DeprecationWarning,
  116. stacklevel=2,
  117. )
  118. handlers: t.Dict = {}
  119. if self.shell is not None:
  120. handlers = getattr(self.shell, "mime_renderers", {})
  121. outputs = self.shell.history_manager.outputs
  122. target_execution_count = self.shell.execution_count - 1
  123. if self._in_post_execute:
  124. # We're in post_execute, so this is likely a matplotlib flush
  125. # Use execution_count - 1 to associate with the cell that created the plot
  126. target_execution_count = self.shell.execution_count - 1
  127. outputs[target_execution_count].append(
  128. HistoryOutput(output_type="display_data", bundle=data)
  129. )
  130. for mime, handler in handlers.items():
  131. if mime in data:
  132. handler(data[mime], metadata.get(mime, None))
  133. return
  134. self._is_publishing = True
  135. if "text/plain" in data:
  136. print(data["text/plain"])
  137. self._is_publishing = False
  138. @property
  139. def is_publishing(self):
  140. return self._is_publishing
  141. def clear_output(self, wait=False):
  142. """Clear the output of the cell receiving output."""
  143. print("\033[2K\r", end="")
  144. sys.stdout.flush()
  145. print("\033[2K\r", end="")
  146. sys.stderr.flush()
  147. class CapturingDisplayPublisher(DisplayPublisher):
  148. """A DisplayPublisher that stores"""
  149. outputs: List = List()
  150. def publish(
  151. self, data, metadata=None, source=None, *, transient=None, update=False
  152. ):
  153. self.outputs.append(
  154. {
  155. "data": data,
  156. "metadata": metadata,
  157. "transient": transient,
  158. "update": update,
  159. }
  160. )
  161. def clear_output(self, wait=False):
  162. super(CapturingDisplayPublisher, self).clear_output(wait)
  163. # empty the list, *do not* reassign a new list
  164. self.outputs.clear()