Skip to content

rich.pretty.install does not work for IPython #3013

@zhengyu-yang

Description

@zhengyu-yang

Version:

Python 3.8.13
IPython 8.12.2

It seems that get_ipython is not in globals when executed in pretty.py, causing the rich text formatter not being installed. It is actually in globals()['__builtins__']. I suggest just use try to replace this check. The problem happens here:

if "get_ipython" in globals():

The fix is:

  try:
      ip = get_ipython()  # type: ignore[name-defined]
      from IPython.core.formatters import BaseFormatter

      class RichFormatter(BaseFormatter):  # type: ignore[misc]
          pprint: bool = True

          def __call__(self, value: Any) -> Any:
              if self.pprint:
                  return _ipy_display_hook(
                      value,
                      console=get_console(),
                      overflow=overflow,
                      indent_guides=indent_guides,
                      max_length=max_length,
                      max_string=max_string,
                      max_depth=max_depth,
                      expand_all=expand_all,
                  )
              else:
                  return repr(value)

      # replace plain text formatter with rich formatter
      rich_formatter = RichFormatter()
      ip.display_formatter.formatters["text/plain"] = rich_formatter
  except NameError:
      sys.displayhook = display_hook

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions