Skip to content

pyscript.display

Display Pythonic content in the browser.

This module provides the display() function for rendering Python objects in the web page. The function introspects objects to determine the appropriate MIME type and rendering method.

Supported MIME types:

  • text/plain: Plain text (HTML-escaped)
  • text/html: HTML content
  • image/png: PNG images as data URLs
  • image/jpeg: JPEG images as data URLs
  • image/svg+xml: SVG graphics
  • application/json: JSON data
  • application/javascript: JavaScript code (discouraged)

The display() function uses standard Python representation methods (_repr_html_, _repr_png_, etc.) to determine how to render objects. Objects can provide a _repr_mimebundle_ method to specify preferred formats like this:

def _repr_mimebundle_(self):
    return {
        "text/html": "<b>Bold HTML</b>",
        "image/png": "<base64-encoded-png-data>",
    }

Heavily inspired by IPython's rich display system.

HTML

Wrap a string to render as unescaped HTML in display(). This is necessary because plain strings are automatically HTML-escaped for safety:

from pyscript import HTML, display


display(HTML("<h1>Hello World</h1>"))

Inspired by IPython.display.HTML.

Source code in pyscript/display.py
class HTML:
    """
    Wrap a string to render as unescaped HTML in `display()`. This is
    necessary because plain strings are automatically HTML-escaped for safety:

    ```python
    from pyscript import HTML, display


    display(HTML("<h1>Hello World</h1>"))
    ```

    Inspired by
    [`IPython.display.HTML`](https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.HTML).
    """

    def __init__(self, html):
        self._html = html

    def _repr_html_(self):
        return self._html

display(*values, target=None, append=True)

Display Python objects in the web page.

  • *values: Python objects to display. Each object is introspected to determine the appropriate rendering method.
  • target: DOM element ID where content should be displayed. If None (default), uses the current script tag's designated output area. This can start with '#' (which will be stripped for compatibility).
  • append: If True (default), add content to existing output. If False, replace existing content before displaying.

When used in a worker, display() requires an explicit target parameter to identify where content will be displayed. If used on the main thread, it automatically uses the current <script> tag as the target. If the script tag has a target attribute, that element will be used instead.

A ValueError is raised if a valid target cannot be found for the current context.

from pyscript import display, HTML


# Display raw HTML.
display(HTML("<h1>Hello, World!</h1>"))

# Display in current script's output area.
display("Hello, World!")

# Display in a specific element.
display("Hello", target="my-div")

# Replace existing content (note the `#`).
display("New content", target="#my-div", append=False)

# Display multiple values in the default target.
display("First", "Second", "Third")
Source code in pyscript/display.py
def display(*values, target=None, append=True):
    """
    Display Python objects in the web page.

    * `*values`: Python objects to display. Each object is introspected to
      determine the appropriate rendering method.
    * `target`: DOM element ID where content should be displayed. If `None`
      (default), uses the current script tag's designated output area. This
      can start with '#' (which will be stripped for compatibility).
    * `append`: If `True` (default), add content to existing output. If
      `False`, replace existing content before displaying.

    When used in a worker, `display()` requires an explicit `target` parameter
    to identify where content will be displayed. If used on the main thread,
    it automatically uses the current `<script>` tag as the target. If the
    script tag has a `target` attribute, that element will be used instead.

    A ValueError is raised if a valid target cannot be found for the current
    context.

    ```python
    from pyscript import display, HTML


    # Display raw HTML.
    display(HTML("<h1>Hello, World!</h1>"))

    # Display in current script's output area.
    display("Hello, World!")

    # Display in a specific element.
    display("Hello", target="my-div")

    # Replace existing content (note the `#`).
    display("New content", target="#my-div", append=False)

    # Display multiple values in the default target.
    display("First", "Second", "Third")
    ```
    """
    if isinstance(target, str):
        # There's a valid target.
        target = target[1:] if target.startswith("#") else target
    elif is_none(target):
        target = current_target()
    element = document.getElementById(target)
    if is_none(element):
        raise ValueError(f"Cannot find element with id='{target}' in the page.")
    # If possible, use a script tag's target attribute.
    if element.tagName == "SCRIPT" and hasattr(element, "target"):
        element = element.target
    # Clear before displaying all values when not appending.
    if not append:
        element.replaceChildren()
    # Add each value.
    for value in values:
        _write_to_dom(element, value, append)