##// END OF EJS Templates
Backport PR #14198 on branch 8.16.x (Revert "fix semicolon detection with no history") (#14199)...
Matthias Bussonnier -
r28449:ff938669 merge
parent child Browse files
Show More
@@ -1,329 +1,336 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 This defines a callable class that IPython uses for `sys.displayhook`.
5 5 """
6 6
7 7 # Copyright (c) IPython Development Team.
8 8 # Distributed under the terms of the Modified BSD License.
9 9
10 10 import builtins as builtin_mod
11 11 import sys
12 12 import io as _io
13 13 import tokenize
14 14
15 15 from traitlets.config.configurable import Configurable
16 16 from traitlets import Instance, Float
17 17 from warnings import warn
18 18
19 19 # TODO: Move the various attributes (cache_size, [others now moved]). Some
20 20 # of these are also attributes of InteractiveShell. They should be on ONE object
21 21 # only and the other objects should ask that one object for their values.
22 22
23 23 class DisplayHook(Configurable):
24 24 """The custom IPython displayhook to replace sys.displayhook.
25 25
26 26 This class does many things, but the basic idea is that it is a callable
27 27 that gets called anytime user code returns a value.
28 28 """
29 29
30 30 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
31 31 allow_none=True)
32 32 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
33 33 allow_none=True)
34 34 cull_fraction = Float(0.2)
35 35
36 36 def __init__(self, shell=None, cache_size=1000, **kwargs):
37 37 super(DisplayHook, self).__init__(shell=shell, **kwargs)
38 38 cache_size_min = 3
39 39 if cache_size <= 0:
40 40 self.do_full_cache = 0
41 41 cache_size = 0
42 42 elif cache_size < cache_size_min:
43 43 self.do_full_cache = 0
44 44 cache_size = 0
45 45 warn('caching was disabled (min value for cache size is %s).' %
46 46 cache_size_min,stacklevel=3)
47 47 else:
48 48 self.do_full_cache = 1
49 49
50 50 self.cache_size = cache_size
51 51
52 52 # we need a reference to the user-level namespace
53 53 self.shell = shell
54
54
55 55 self._,self.__,self.___ = '','',''
56 56
57 57 # these are deliberately global:
58 58 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
59 59 self.shell.user_ns.update(to_user_ns)
60 60
61 61 @property
62 62 def prompt_count(self):
63 63 return self.shell.execution_count
64 64
65 65 #-------------------------------------------------------------------------
66 66 # Methods used in __call__. Override these methods to modify the behavior
67 67 # of the displayhook.
68 68 #-------------------------------------------------------------------------
69 69
70 70 def check_for_underscore(self):
71 71 """Check if the user has set the '_' variable by hand."""
72 72 # If something injected a '_' variable in __builtin__, delete
73 73 # ipython's automatic one so we don't clobber that. gettext() in
74 74 # particular uses _, so we need to stay away from it.
75 75 if '_' in builtin_mod.__dict__:
76 76 try:
77 77 user_value = self.shell.user_ns['_']
78 78 if user_value is not self._:
79 79 return
80 80 del self.shell.user_ns['_']
81 81 except KeyError:
82 82 pass
83 83
84 84 def quiet(self):
85 85 """Should we silence the display hook because of ';'?"""
86 if self.exec_result is not None:
87 return self.semicolon_at_end_of_expression(self.exec_result.info.raw_cell)
88 return False
86 # do not print output if input ends in ';'
87
88 try:
89 cell = self.shell.history_manager.input_hist_parsed[-1]
90 except IndexError:
91 # some uses of ipshellembed may fail here
92 return False
93
94 return self.semicolon_at_end_of_expression(cell)
89 95
90 96 @staticmethod
91 97 def semicolon_at_end_of_expression(expression):
92 98 """Parse Python expression and detects whether last token is ';'"""
93 99
94 100 sio = _io.StringIO(expression)
95 101 tokens = list(tokenize.generate_tokens(sio.readline))
96 102
97 103 for token in reversed(tokens):
98 104 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
99 105 continue
100 106 if (token[0] == tokenize.OP) and (token[1] == ';'):
101 107 return True
102 108 else:
103 109 return False
104 110
105 111 def start_displayhook(self):
106 112 """Start the displayhook, initializing resources."""
107 113 pass
108 114
109 115 def write_output_prompt(self):
110 116 """Write the output prompt.
111 117
112 118 The default implementation simply writes the prompt to
113 119 ``sys.stdout``.
114 120 """
115 121 # Use write, not print which adds an extra space.
116 122 sys.stdout.write(self.shell.separate_out)
117 123 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
118 124 if self.do_full_cache:
119 125 sys.stdout.write(outprompt)
120 126
121 127 def compute_format_data(self, result):
122 128 """Compute format data of the object to be displayed.
123 129
124 130 The format data is a generalization of the :func:`repr` of an object.
125 131 In the default implementation the format data is a :class:`dict` of
126 132 key value pair where the keys are valid MIME types and the values
127 133 are JSON'able data structure containing the raw data for that MIME
128 134 type. It is up to frontends to determine pick a MIME to to use and
129 135 display that data in an appropriate manner.
130 136
131 137 This method only computes the format data for the object and should
132 138 NOT actually print or write that to a stream.
133 139
134 140 Parameters
135 141 ----------
136 142 result : object
137 143 The Python object passed to the display hook, whose format will be
138 144 computed.
139 145
140 146 Returns
141 147 -------
142 148 (format_dict, md_dict) : dict
143 149 format_dict is a :class:`dict` whose keys are valid MIME types and values are
144 150 JSON'able raw data for that MIME type. It is recommended that
145 151 all return values of this should always include the "text/plain"
146 152 MIME type representation of the object.
147 153 md_dict is a :class:`dict` with the same MIME type keys
148 154 of metadata associated with each output.
149 155
150 156 """
151 157 return self.shell.display_formatter.format(result)
152 158
153 159 # This can be set to True by the write_output_prompt method in a subclass
154 160 prompt_end_newline = False
155 161
156 162 def write_format_data(self, format_dict, md_dict=None) -> None:
157 163 """Write the format data dict to the frontend.
158 164
159 165 This default version of this method simply writes the plain text
160 166 representation of the object to ``sys.stdout``. Subclasses should
161 167 override this method to send the entire `format_dict` to the
162 168 frontends.
163 169
164 170 Parameters
165 171 ----------
166 172 format_dict : dict
167 173 The format dict for the object passed to `sys.displayhook`.
168 174 md_dict : dict (optional)
169 175 The metadata dict to be associated with the display data.
170 176 """
171 177 if 'text/plain' not in format_dict:
172 178 # nothing to do
173 179 return
174 180 # We want to print because we want to always make sure we have a
175 181 # newline, even if all the prompt separators are ''. This is the
176 182 # standard IPython behavior.
177 183 result_repr = format_dict['text/plain']
178 184 if '\n' in result_repr:
179 185 # So that multi-line strings line up with the left column of
180 186 # the screen, instead of having the output prompt mess up
181 187 # their first line.
182 188 # We use the prompt template instead of the expanded prompt
183 189 # because the expansion may add ANSI escapes that will interfere
184 190 # with our ability to determine whether or not we should add
185 191 # a newline.
186 192 if not self.prompt_end_newline:
187 193 # But avoid extraneous empty lines.
188 194 result_repr = '\n' + result_repr
189 195
190 196 try:
191 197 print(result_repr)
192 198 except UnicodeEncodeError:
193 199 # If a character is not supported by the terminal encoding replace
194 200 # it with its \u or \x representation
195 201 print(result_repr.encode(sys.stdout.encoding,'backslashreplace').decode(sys.stdout.encoding))
196 202
197 203 def update_user_ns(self, result):
198 204 """Update user_ns with various things like _, __, _1, etc."""
199 205
200 206 # Avoid recursive reference when displaying _oh/Out
201 207 if self.cache_size and result is not self.shell.user_ns['_oh']:
202 208 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
203 209 self.cull_cache()
204 210
205 211 # Don't overwrite '_' and friends if '_' is in __builtin__
206 212 # (otherwise we cause buggy behavior for things like gettext). and
207 213 # do not overwrite _, __ or ___ if one of these has been assigned
208 214 # by the user.
209 215 update_unders = True
210 216 for unders in ['_'*i for i in range(1,4)]:
211 217 if not unders in self.shell.user_ns:
212 218 continue
213 219 if getattr(self, unders) is not self.shell.user_ns.get(unders):
214 220 update_unders = False
215 221
216 222 self.___ = self.__
217 223 self.__ = self._
218 224 self._ = result
219 225
220 226 if ('_' not in builtin_mod.__dict__) and (update_unders):
221 227 self.shell.push({'_':self._,
222 228 '__':self.__,
223 229 '___':self.___}, interactive=False)
224 230
225 231 # hackish access to top-level namespace to create _1,_2... dynamically
226 232 to_main = {}
227 233 if self.do_full_cache:
228 234 new_result = '_%s' % self.prompt_count
229 235 to_main[new_result] = result
230 236 self.shell.push(to_main, interactive=False)
231 237 self.shell.user_ns['_oh'][self.prompt_count] = result
232 238
233 239 def fill_exec_result(self, result):
234 240 if self.exec_result is not None:
235 241 self.exec_result.result = result
236 242
237 243 def log_output(self, format_dict):
238 244 """Log the output."""
239 245 if 'text/plain' not in format_dict:
240 246 # nothing to do
241 247 return
242 248 if self.shell.logger.log_output:
243 249 self.shell.logger.log_write(format_dict['text/plain'], 'output')
244 250 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
245 251 format_dict['text/plain']
246 252
247 253 def finish_displayhook(self):
248 254 """Finish up all displayhook activities."""
249 255 sys.stdout.write(self.shell.separate_out2)
250 256 sys.stdout.flush()
251 257
252 258 def __call__(self, result=None):
253 259 """Printing with history cache management.
254 260
255 261 This is invoked every time the interpreter needs to print, and is
256 262 activated by setting the variable sys.displayhook to it.
257 263 """
258 264 self.check_for_underscore()
259 265 if result is not None and not self.quiet():
260 266 self.start_displayhook()
261 267 self.write_output_prompt()
262 268 format_dict, md_dict = self.compute_format_data(result)
263 269 self.update_user_ns(result)
264 270 self.fill_exec_result(result)
265 271 if format_dict:
266 272 self.write_format_data(format_dict, md_dict)
267 273 self.log_output(format_dict)
268 274 self.finish_displayhook()
269 275
270 276 def cull_cache(self):
271 277 """Output cache is full, cull the oldest entries"""
272 278 oh = self.shell.user_ns.get('_oh', {})
273 279 sz = len(oh)
274 280 cull_count = max(int(sz * self.cull_fraction), 2)
275 281 warn('Output cache limit (currently {sz} entries) hit.\n'
276 282 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
277
283
278 284 for i, n in enumerate(sorted(oh)):
279 285 if i >= cull_count:
280 286 break
281 287 self.shell.user_ns.pop('_%i' % n, None)
282 288 oh.pop(n, None)
289
283 290
284 291 def flush(self):
285 292 if not self.do_full_cache:
286 293 raise ValueError("You shouldn't have reached the cache flush "
287 294 "if full caching is not enabled!")
288 295 # delete auto-generated vars from global namespace
289 296
290 297 for n in range(1,self.prompt_count + 1):
291 298 key = '_'+repr(n)
292 299 try:
293 300 del self.shell.user_ns_hidden[key]
294 301 except KeyError:
295 302 pass
296 303 try:
297 304 del self.shell.user_ns[key]
298 305 except KeyError:
299 306 pass
300 307 # In some embedded circumstances, the user_ns doesn't have the
301 308 # '_oh' key set up.
302 309 oh = self.shell.user_ns.get('_oh', None)
303 310 if oh is not None:
304 311 oh.clear()
305 312
306 313 # Release our own references to objects:
307 314 self._, self.__, self.___ = '', '', ''
308 315
309 316 if '_' not in builtin_mod.__dict__:
310 317 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
311 318 import gc
312 319 # TODO: Is this really needed?
313 320 # IronPython blocks here forever
314 321 if sys.platform != "cli":
315 322 gc.collect()
316 323
317 324
318 325 class CapturingDisplayHook(object):
319 326 def __init__(self, shell, outputs=None):
320 327 self.shell = shell
321 328 if outputs is None:
322 329 outputs = []
323 330 self.outputs = outputs
324 331
325 332 def __call__(self, result=None):
326 333 if result is None:
327 334 return
328 335 format_dict, md_dict = self.shell.display_formatter.format(result)
329 336 self.outputs.append({ 'data': format_dict, 'metadata': md_dict })
General Comments 0
You need to be logged in to leave comments. Login now