Skip to content

Commit

Permalink
displayhook - get reference to the actual executed cell
Browse files Browse the repository at this point in the history
the raw_cell might need transformation and cannot be tokenized.
Fixes ipython#7256
  • Loading branch information
idanpa committed Oct 1, 2023
1 parent b7c9c36 commit 855faa9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
7 changes: 4 additions & 3 deletions IPython/core/displayhook.py
Expand Up @@ -13,7 +13,7 @@
import tokenize

from traitlets.config.configurable import Configurable
from traitlets import Instance, Float
from traitlets import Instance, Unicode, Float
from warnings import warn

# TODO: Move the various attributes (cache_size, [others now moved]). Some
Expand All @@ -31,6 +31,7 @@ class DisplayHook(Configurable):
allow_none=True)
exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
allow_none=True)
exec_cell = Unicode(allow_none=True)
cull_fraction = Float(0.2)

def __init__(self, shell=None, cache_size=1000, **kwargs):
Expand Down Expand Up @@ -83,8 +84,8 @@ def check_for_underscore(self):

def quiet(self):
"""Should we silence the display hook because of ';'?"""
if self.exec_result is not None:
return self.semicolon_at_end_of_expression(self.exec_result.info.raw_cell)
if self.exec_result is not None and self.exec_result.cell is not None:
return self.semicolon_at_end_of_expression(self.exec_result.cell)
return False

@staticmethod
Expand Down
3 changes: 3 additions & 0 deletions IPython/core/interactiveshell.py
Expand Up @@ -255,6 +255,7 @@ class ExecutionResult(object):
error_in_exec: Optional[BaseException] = None
info = None
result = None
cell = None

def __init__(self, info):
self.info = info
Expand Down Expand Up @@ -3224,6 +3225,8 @@ def error_before_exec(value):
else:
cell = raw_cell

result.cell = cell

# Do NOT store paste/cpaste magic history
if "get_ipython().run_line_magic(" in cell and "paste" in cell:
store_history = False
Expand Down
28 changes: 28 additions & 0 deletions IPython/core/tests/test_magic.py
Expand Up @@ -1546,3 +1546,31 @@ def get_data(self, path):
assert output == captured.stdout

sys.meta_path.pop(0)


def doctest_magic_output_can_be_silenced():
"""Test ...
In [1]: from IPython.core.magic import register_line_magic, output_can_be_silenced
In [2]: @register_line_magic
...: def echo_magic(line):
...: return line
...:
In [3]: @register_line_magic
...: @output_can_be_silenced
...: def echo_magic_can_be_silenced(line):
...: return line
...:
In [4]: %echo_magic hello
Out[4]: 'hello'
In [5]: %echo_magic hello;
Out[5]: 'hello;'
In [6]: %echo_magic_can_be_silenced hello;
In [7]: %echo_magic_can_be_silenced hello
Out[7]: 'hello'
"""

0 comments on commit 855faa9

Please sign in to comment.