From fc0c914e636dff60149d152926e909f8c8e29a09 Mon Sep 17 00:00:00 2001 From: Jason Grout Date: Tue, 27 Mar 2018 14:10:28 -0700 Subject: [PATCH] Use _repr_mimebundle_ in IPython 6.1 or later. Fixes #1811 --- ipywidgets/widgets/widget.py | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/ipywidgets/widgets/widget.py b/ipywidgets/widgets/widget.py index b504793bb32..b3f7e8a5918 100644 --- a/ipywidgets/widgets/widget.py +++ b/ipywidgets/widgets/widget.py @@ -9,6 +9,7 @@ import collections import sys +from IPython import version_info as ipython_version_info from IPython.core.getipython import get_ipython from ipykernel.comm import Comm from traitlets.utils.importstring import import_item @@ -19,6 +20,7 @@ from IPython.display import display from json import loads as jsonloads, dumps as jsondumps + from base64 import standard_b64decode, standard_b64encode from .._version import __protocol_version__, __jupyter_widgets_base_version__ @@ -466,6 +468,7 @@ def close(self): self.comm.close() self.comm = None self._ipython_display_ = None + self._repr_mimebundle_ = None def send_state(self, key=None): """Sends the widget state, or a piece of it, to the front-end, if it exists. @@ -697,9 +700,12 @@ def _trait_from_json(x, self): """Convert json values to objects.""" return x - def _ipython_display_(self, **kwargs): - """Called when `IPython.display.display` is called on the widget.""" + def _repr_mimebundle_(self, **kwargs): + """Called when `IPython.display.display` is called.""" if self._view_name is not None: + # This callback now happens *before* the actual display call, + # whereas before it happened *after* the display call. + self._handle_displayed(**kwargs) plaintext = repr(self) if len(plaintext) > 110: @@ -717,9 +723,21 @@ def _ipython_display_(self, **kwargs): 'model_id': self._model_id } } - display(data, raw=True) + return data - self._handle_displayed(**kwargs) + def _ipython_display_(self, **kwargs): + """Called when `IPython.display.display` is called on a widget. + + Note: if we are in IPython 6.1 or later, we return NotImplemented so + that _repr_mimebundle_ is used directly. + """ + if (ipython_version_info[0] > 6 + or (ipython_version_info[0] == 6 and ipython_version_info[1] >= 1)): + raise NotImplementedError + + data = self._repr_mimebundle_(**kwargs) + if data: + display(data, raw=True) def _send(self, msg, buffers=None): """Sends a message to the model in the front-end."""