Skip to content

Commit

Permalink
Don't display() in jupyter when in a capture
Browse files Browse the repository at this point in the history
Fixes #3274
  • Loading branch information
NickCrews committed Aug 6, 2024
1 parent e1e6d74 commit b5ef155
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions rich/jupyter.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ def escape(text: str) -> str:

def display(segments: Iterable[Segment], text: str) -> None:
"""Render segments to Jupyter."""
segments = list(segments)
if not segments and not text:
# display() always prints a newline, so if there is no content then
# we don't want a single newline appearing.
# See https://github.com/Textualize/rich/issues/3274
return None
html = _render_segments(segments)
jupyter_renderable = JupyterRenderable(html, text)
try:
Expand Down
19 changes: 19 additions & 0 deletions tests/test_jupyter.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,22 @@ def test_jupyter_lines_env():
console = Console(
width=40, _environ={"JUPYTER_LINES": "broken"}, force_jupyter=True
)


def test_jupyter_capture(monkeypatch):
# If inside a capture, ipython's display shouldn't be called,
# or we would get spurious newlines.
# See https://github.com/Textualize/rich/issues/3274
called = False

def mock_display(*args, **kwargs):
nonlocal called
called = True

monkeypatch.setattr("IPython.display.display", mock_display)
console = Console(force_jupyter=True)
with console.capture():
console.print("foo")
assert not called
console.print("foo")
assert called

0 comments on commit b5ef155

Please sign in to comment.