Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't display() spurious newlines in jupyter #3329

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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