Skip to content

Instantly share code, notes, and snippets.

@ignamv
Created November 11, 2023 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ignamv/1749c55d78944edcedbfd4455b77019f to your computer and use it in GitHub Desktop.
Save ignamv/1749c55d78944edcedbfd4455b77019f to your computer and use it in GitHub Desktop.
Collapsible Jupyter display for hierarchies of dict/list/tuple
import html
def to_html(x):
if isinstance(x, (list, tuple, dict)):
if isinstance(x, (list, tuple)):
elements = "".join(
f"<li>[{ii}]: {to_html(elem)}</li>" for ii, elem in enumerate(x)
)
else:
elements = "".join(f"<li>{k!r}: {to_html(v)}</li>" for k, v in x.items())
summary = repr(x)
if len(summary) > 100:
summary = summary[:100] + "[...]"
return f'<details style="display:inline-block; vertical-align: top;"><summary>{summary}</summary><ul>{elements}</ul></details>'
return html.escape(repr(x))
class ObjectBrowser:
"""
Collapsible Jupyter display for hierarchies of dict/list/tuple
Example
=======
>>> ObjectBrowser({1: 2, "a": "b", "c": [2, 3, [5]]})
"""
def __init__(self, x):
self.x = x
def _repr_html_(self):
return f"<code>{to_html(self.x)}</code>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment