Is there a way to detect when running in a with ipywidgets.Output() block?

I have a library that uses IPython.display.HTML and it works great for most users. However, when a user wants to use with ipywidgets.Output(), it would be better to use ipywidgets.HTML. Is there a way to detect when this is occurring?

To clarify:

import ipywidgets

def in_output_block():
    # What goes here?

out = ipywidgets.Output()

with out:
   assert in_output_block() is True

assert in_output_block() is False

Hi,

I needed to solve the same problem and found your question.

After trial and error with OpenAI o3 and GPT 5 I have this solution:

def _outputs_capturing_this_code():
    """
    Returns list of ipywidgets.widgets.Output instances currently registered with ipython.
    """

    from IPython import get_ipython  # type: ignore
    from ipywidgets import Output

    # Avoid deprecation warning: access the private registry directly
    from ipywidgets.widgets.widget import _instances

    ip = get_ipython()
    kernel = getattr(ip, "kernel", None)
    if kernel is None:
        return []

    # ipykernel ≥6
    parent = getattr(kernel, "get_parent", lambda: None)()
    # Fallback for ipykernel <6
    if parent is None:
        parent = getattr(kernel, "_parent_header", None)
    if not parent or "header" not in parent:
        return []

    cur_msg_id = parent["header"].get("msg_id", "")
    return [
        w for w in _instances.values()
        if isinstance(w, Output) and getattr(w, "msg_id", "") == cur_msg_id
    ]


def in_output_block():
    return bool(_outputs_capturing_this_code())

It works with ipywidgets 8.1.3. I tested it in VS Code notebooks (on Linux) and jupyter-lab 4.0.13.

Let me know if it works for you.

PS
For more details see this discussion with GPT 5 about how Output works.

1 Like