Skip to content

Commit

Permalink
chore: gut repr code; get rid of duplicated tracebacks
Browse files Browse the repository at this point in the history
  • Loading branch information
cpcloud committed Sep 3, 2024
1 parent 48e7fa1 commit 77220bf
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 43 deletions.
11 changes: 5 additions & 6 deletions ibis/backends/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1212,12 +1212,11 @@ def test_repr_mimebundle(alltypes, interactive, expr_type, monkeypatch):
else:
expr = alltypes.select("date_string_col")

reprs = expr._repr_mimebundle_(include=["text/plain", "text/html"], exclude=[])
for format in ["text/plain", "text/html"]:
if interactive:
assert "r0.date_string_col" not in reprs[format]
else:
assert "r0.date_string_col" in reprs[format]
text = expr._repr_html_()
if interactive:
assert "r0.date_string_col" not in text
else:
assert "r0.date_string_col" in text


@pytest.mark.never(
Expand Down
49 changes: 16 additions & 33 deletions ibis/expr/types/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@

import contextlib
import os
import traceback
import webbrowser
from typing import TYPE_CHECKING, Any, NoReturn

from public import public

import ibis
import ibis.expr.operations as ops
from ibis.common.annotations import ValidationError
from ibis.common.exceptions import IbisError, TranslationError
Expand All @@ -35,37 +33,10 @@
from ibis.expr.visualize import EdgeAttributeGetter, NodeAttributeGetter


try:
from rich.jupyter import JupyterMixin
except ImportError:

class _FixedTextJupyterMixin:
"""No-op when rich is not installed."""
else:

class _FixedTextJupyterMixin(JupyterMixin):
"""JupyterMixin adds a spurious newline to text, this fixes the issue."""

def _repr_mimebundle_(self, *args, **kwargs):
try:
bundle = super()._repr_mimebundle_(*args, **kwargs)
bundle["text/plain"] = bundle["text/plain"].rstrip()
return bundle
except Exception as e:
# In IPython (but not other REPLs), exceptions inside of
# _repr_mimebundle_ are swallowed to allow calling several display
# functions and choosing to display the "best" based on some priority.
#
# This means that exceptions during interactive repr are silently caught.
# We can't stop the exception from being swallowed, but at least we can print them.
traceback.print_exc()
raise e


def _capture_rich_renderable(renderable: RenderableType) -> str:
from rich.console import Console
from rich import get_console

console = Console(force_terminal=False)
console = get_console()
with console.capture() as capture:
console.print(renderable)
return capture.get().rstrip()
Expand All @@ -79,18 +50,30 @@ class Expr(Immutable, Coercible):
_arg: ops.Node

def _noninteractive_repr(self) -> str:
if ibis.options.repr.show_variables:
if opts.repr.show_variables:
scope = get_defining_scope(self, types=Expr)
else:
scope = None
return pretty(self.op(), scope=scope)

def __repr__(self) -> str:
if ibis.options.interactive:
if opts.interactive:
return _capture_rich_renderable(self)
else:
return self._noninteractive_repr()

def _repr_pretty_(self, p, cycle):
p.text(_capture_rich_renderable(self))

def _repr_html_(self):
from rich import get_console
from rich.jupyter import _render_segments

console = get_console()
segments = list(console.render(self, console.options))
html = _render_segments(segments)
return html.rstrip()

def __rich_console__(self, console: Console, options: ConsoleOptions):
if console.is_jupyter:
# Rich infers a console width in jupyter notebooks, but since
Expand Down
4 changes: 2 additions & 2 deletions ibis/expr/types/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from ibis.common.deferred import Deferred, _, deferrable
from ibis.common.grounds import Singleton
from ibis.expr.rewrites import rewrite_window_input
from ibis.expr.types.core import Expr, _binop, _FixedTextJupyterMixin, _is_null_literal
from ibis.expr.types.core import Expr, _binop, _is_null_literal
from ibis.util import deprecated, promote_list, warn_deprecated

if TYPE_CHECKING:
Expand Down Expand Up @@ -1367,7 +1367,7 @@ def _repr_html_(self) -> str | None:


@public
class Column(Value, _FixedTextJupyterMixin):
class Column(Value):
# Higher than numpy & dask objects
__array_priority__ = 20

Expand Down
4 changes: 2 additions & 2 deletions ibis/expr/types/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from ibis.common.deferred import Deferred, Resolver
from ibis.common.selectors import Expandable, Selector
from ibis.expr.rewrites import DerefMap
from ibis.expr.types.core import Expr, _FixedTextJupyterMixin
from ibis.expr.types.core import Expr
from ibis.expr.types.generic import Value, literal
from ibis.expr.types.temporal import TimestampColumn
from ibis.util import deprecated
Expand Down Expand Up @@ -140,7 +140,7 @@ def unwrap_aliases(values: Iterator[ir.Value]) -> Mapping[str, ir.Value]:


@public
class Table(Expr, _FixedTextJupyterMixin):
class Table(Expr):
"""An immutable and lazy dataframe.
Analogous to a SQL table or a pandas DataFrame. A table expression contains
Expand Down

0 comments on commit 77220bf

Please sign in to comment.