Skip to content

Commit

Permalink
Use _repr_mimebundle_ in IPython 6.1 or later.
Browse files Browse the repository at this point in the history
  • Loading branch information
jasongrout committed Mar 28, 2018
1 parent 04323bd commit b7aac7f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
8 changes: 6 additions & 2 deletions ipywidgets/widgets/tests/test_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

"""Test Widget."""

from IPython import version_info
from IPython.core.interactiveshell import InteractiveShell
from IPython.display import display
from IPython.utils.capture import capture_output

from ..widget import Widget


Expand All @@ -19,6 +19,10 @@ def test_no_widget_view():
w = Widget()
display(w)

assert cap.outputs == [], repr(cap.outputs)
if version_info >= (6, 1):
assert len(cap.outputs) == 1 and cap.outputs[0].data['text/plain'] == 'Widget()', repr(cap.outputs)
else:
assert cap.outputs == [], repr(cap.outputs)

assert cap.stdout == '', repr(cap.stdout)
assert cap.stderr == '', repr(cap.stderr)
24 changes: 20 additions & 4 deletions ipywidgets/widgets/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -466,6 +467,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.
Expand Down Expand Up @@ -697,9 +699,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:
Expand All @@ -717,9 +722,20 @@ 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 >= (6, 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."""
Expand Down

0 comments on commit b7aac7f

Please sign in to comment.