diff --git a/ipywidgets/widgets/tests/test_widget_image.py b/ipywidgets/widgets/tests/test_widget_image.py index c5d810eaca..2891f2b803 100644 --- a/ipywidgets/widgets/tests/test_widget_image.py +++ b/ipywidgets/widgets/tests/test_widget_image.py @@ -130,6 +130,20 @@ def test_format_inference_overridable(): assert img.format == 'gif' +def test_value_repr_length(): + with get_logo_png() as LOGO_PNG: + with open(LOGO_PNG, 'rb') as f: + img = Image.from_file(f) + assert len(img.__repr__()) < 120 + assert img.__repr__().endswith("...')") + + +def test_value_repr_url(): + img = Image.from_url(b'https://jupyter.org/assets/main-logo.svg') + + assert 'https://jupyter.org/assets/main-logo.svg' in img.__repr__() + + # Helper functions def get_hash_hex(byte_str): m = hashlib.new('sha256') diff --git a/ipywidgets/widgets/widget_image.py b/ipywidgets/widgets/widget_image.py index d1c7b577fd..b45b57c3ff 100644 --- a/ipywidgets/widgets/widget_image.py +++ b/ipywidgets/widgets/widget_image.py @@ -6,6 +6,7 @@ Represents an image in the frontend using a widget. """ import mimetypes +import hashlib from .widget_core import CoreWidget from .domwidget import DOMWidget @@ -128,3 +129,25 @@ def _guess_format(cls, filename): return mtype[len('image/'):] except Exception: return None + + def __repr__(self): + # Truncate the value in the repr, since it will + # typically be very, very large. + class_name = self.__class__.__name__ + + # Return value first like a ValueWidget + signature = [] + sig_value = repr(self.value) + prefix, rest = sig_value.split("'", 1) + content = rest[:-1] + if len(content) > 100: + sig_value = "{}'{}...'".format(prefix, content[0:100]) + signature.append('%s=%s' % ('value', sig_value)) + + for key in super(Image, self)._repr_keys(): + if key == 'value': + continue + value = str(getattr(self, key)) + signature.append('%s=%r' % (key, value)) + signature = ', '.join(signature) + return '%s(%s)' % (class_name, signature)