Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Thread safe kernel side Output widget #3759

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions python/ipywidgets/ipywidgets/widgets/tests/test_widget_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,16 @@ def test_append_display_data():
},
)
assert widget.outputs == expected1 or widget.outputs == expected2


def test_kernel_side_output():
output = widget_output.Output()
with output:
print("snakes!")
assert output.outputs == (
{
'output_type': 'stream',
'name': 'stdout',
'text': 'snakes!
}
)
21 changes: 21 additions & 0 deletions python/ipywidgets/ipywidgets/widgets/widget_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ def func():

__counter = 0

def __init__(self, *args, **kwargs):
super(Output, self).__init__(*args, **kwargs)
self._hooks = []

def clear_output(self, *pargs, **kwargs):
"""
Clear the content of the output widget.
Expand Down Expand Up @@ -108,6 +112,17 @@ def __enter__(self):
"""Called upon entering output widget context manager."""
self._flush()
ip = get_ipython()
if hasattr(ip.display_pub, "register_hook") and hasattr(sys.stdout, "register_hook"):
def hook(msg):
if msg["msg_type"] == "display_data":
self.outputs += ({"output_type": "display_data", "data": msg["content"]["data"], "metadata": msg["content"]["metadata"]},)
return None
return msg
ip.display_pub.register_hook(hook)
sys.stdout.register_hook(hook)
self._hooks.append(hook)
return

kernel = None
if ip and getattr(ip, "kernel", None) is not None:
kernel = ip.kernel
Expand Down Expand Up @@ -147,6 +162,12 @@ def __exit__(self, etype, evalue, tb):
u'ename': etype.__name__
})
self._flush()
if self._hooks:
ip = get_ipython()
hook = self._hooks.pop()
ip.display_pub.unregister_hook(hook)
sys.stdout.unregister_hook(hook)
return
self.__counter -= 1
if self.__counter == 0:
self.msg_id = ''
Expand Down