Skip to content

utils

Functions:

  • display

    Displays objects in a rich format, depending on the environment.

display(*args, opt: Literal['math', 'dict'] | None = None, **kwargs) -> None

Displays objects in a rich format, depending on the environment.

This function displays objects using IPython's display mechanism if available, otherwise it falls back to sympy.pprint.

Parameters:

  • *args

    The objects to display.

  • opt (Literal['math', 'dict'] | None, default: None ) –
    • If "math", displays the object as a math expression.
    • If "dict", generates a LaTeX representation of the dictionary for display.
    • If none, assumes the object can be passed into IPython's [display][display] function directly.
  • **kwargs

    Additional keyword arguments to pass to the display function.

See Also
Source code in src/ma1522/utils.py
Python
def display(*args, opt: Literal["math", "dict"] | None = None, **kwargs) -> None:
    """Displays objects in a rich format, depending on the environment.

    This function displays objects using IPython's [`display`][IPython.display] mechanism if available,
    otherwise it falls back to [`sympy.pprint`][sympy.printing.pretty.pretty.PrettyPrinter].

    Args:
        *args: The objects to display.
        opt:

            - If "math", displays the object as a math expression.
            - If "dict", generates a LaTeX representation of the dictionary for display.
            - If none, assumes the object can be passed into IPython's [`display`][] function directly.
        **kwargs: Additional keyword arguments to pass to the display function.

    See Also:
        - [`IPython.display.display`][IPython.display]: The class used to display
            objects in IPython environments.
        - [`sympy.pprint`][sympy.printing.pretty.pretty.PrettyPrinter]: The class used to pretty-print
            objects in non-IPython environments.
    """
    if _is_IPython():
        import IPython.display

        if opt == "math":
            # Display the object as a math expression
            IPython.display.display(IPython.display.Math(*args, **kwargs))
        elif opt == "dict":
            # Generate a LaTeX representation of the dictionary
            from sympy.printing.latex import LatexPrinter

            printer = kwargs.pop("printer", LatexPrinter())
            for arg in args:
                if not isinstance(arg, dict):
                    continue
                IPython.display.display(
                    IPython.display.Math(_gen_latex_repr_dict(arg, printer=printer))
                )
        else:
            IPython.display.display(*args, **kwargs)
    else:
        sym.pprint(*args, **kwargs)