Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/IPython/core/displayhook.py: 21%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

172 statements  

1"""Displayhook for IPython. 

2 

3This defines a callable class that IPython uses for `sys.displayhook`. 

4""" 

5 

6# Copyright (c) IPython Development Team. 

7# Distributed under the terms of the Modified BSD License. 

8 

9import builtins as builtin_mod 

10import sys 

11import io as _io 

12import tokenize 

13 

14from traitlets.config.configurable import Configurable 

15from traitlets import Instance, Float 

16from warnings import warn 

17 

18 

19# TODO: Move the various attributes (cache_size, [others now moved]). Some 

20# of these are also attributes of InteractiveShell. They should be on ONE object 

21# only and the other objects should ask that one object for their values. 

22 

23class DisplayHook(Configurable): 

24 """The custom IPython displayhook to replace sys.displayhook. 

25 

26 This class does many things, but the basic idea is that it is a callable 

27 that gets called anytime user code returns a value. 

28 """ 

29 

30 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', 

31 allow_none=True) 

32 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult', 

33 allow_none=True) 

34 cull_fraction = Float(0.2) 

35 

36 def __init__(self, shell=None, cache_size=1000, **kwargs): 

37 super().__init__(shell=shell, **kwargs) 

38 self._is_active = False 

39 cache_size_min = 3 

40 if cache_size <= 0: 

41 self.do_full_cache = 0 

42 cache_size = 0 

43 elif cache_size < cache_size_min: 

44 self.do_full_cache = 0 

45 cache_size = 0 

46 warn('caching was disabled (min value for cache size is %s).' % 

47 cache_size_min,stacklevel=3) 

48 else: 

49 self.do_full_cache = 1 

50 

51 self.cache_size = cache_size 

52 

53 # we need a reference to the user-level namespace 

54 self.shell = shell 

55 

56 self._,self.__,self.___ = '','','' 

57 

58 # these are deliberately global: 

59 to_user_ns = {'_':self._,'__':self.__,'___':self.___} 

60 self.shell.user_ns.update(to_user_ns) 

61 

62 @property 

63 def prompt_count(self): 

64 return self.shell.execution_count - 1 

65 

66 #------------------------------------------------------------------------- 

67 # Methods used in __call__. Override these methods to modify the behavior 

68 # of the displayhook. 

69 #------------------------------------------------------------------------- 

70 

71 def check_for_underscore(self): 

72 """Check if the user has set the '_' variable by hand.""" 

73 # If something injected a '_' variable in __builtin__, delete 

74 # ipython's automatic one so we don't clobber that. gettext() in 

75 # particular uses _, so we need to stay away from it. 

76 if '_' in builtin_mod.__dict__: 

77 try: 

78 user_value = self.shell.user_ns['_'] 

79 if user_value is not self._: 

80 return 

81 del self.shell.user_ns['_'] 

82 except KeyError: 

83 pass 

84 

85 def quiet(self): 

86 """Should we silence the display hook because of ';'?""" 

87 # do not print output if input ends in ';' 

88 

89 try: 

90 cell = self.shell.history_manager.input_hist_parsed[-1] 

91 except IndexError: 

92 # some uses of ipshellembed may fail here 

93 return False 

94 

95 return self.semicolon_at_end_of_expression(cell) 

96 

97 @staticmethod 

98 def semicolon_at_end_of_expression(expression): 

99 """Parse Python expression and detects whether last token is ';'""" 

100 

101 sio = _io.StringIO(expression) 

102 tokens = list(tokenize.generate_tokens(sio.readline)) 

103 

104 for token in reversed(tokens): 

105 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): 

106 continue 

107 if (token[0] == tokenize.OP) and (token[1] == ';'): 

108 return True 

109 else: 

110 return False 

111 

112 def start_displayhook(self): 

113 """Start the displayhook, initializing resources.""" 

114 self._is_active = True 

115 

116 @property 

117 def is_active(self): 

118 return self._is_active 

119 

120 def write_output_prompt(self): 

121 """Write the output prompt. 

122 

123 The default implementation simply writes the prompt to 

124 ``sys.stdout``. 

125 """ 

126 # Use write, not print which adds an extra space. 

127 sys.stdout.write(self.shell.separate_out) 

128 outprompt = f'Out[{self.shell.execution_count - 1}]: ' 

129 if self.do_full_cache: 

130 sys.stdout.write(outprompt) 

131 

132 def compute_format_data(self, result): 

133 """Compute format data of the object to be displayed. 

134 

135 The format data is a generalization of the :func:`repr` of an object. 

136 In the default implementation the format data is a :class:`dict` of 

137 key value pair where the keys are valid MIME types and the values 

138 are JSON'able data structure containing the raw data for that MIME 

139 type. It is up to frontends to determine pick a MIME to to use and 

140 display that data in an appropriate manner. 

141 

142 This method only computes the format data for the object and should 

143 NOT actually print or write that to a stream. 

144 

145 Parameters 

146 ---------- 

147 result : object 

148 The Python object passed to the display hook, whose format will be 

149 computed. 

150 

151 Returns 

152 ------- 

153 (format_dict, md_dict) : dict 

154 format_dict is a :class:`dict` whose keys are valid MIME types and values are 

155 JSON'able raw data for that MIME type. It is recommended that 

156 all return values of this should always include the "text/plain" 

157 MIME type representation of the object. 

158 md_dict is a :class:`dict` with the same MIME type keys 

159 of metadata associated with each output. 

160 

161 """ 

162 return self.shell.display_formatter.format(result) 

163 

164 # This can be set to True by the write_output_prompt method in a subclass 

165 prompt_end_newline = False 

166 

167 def write_format_data(self, format_dict, md_dict=None) -> None: 

168 """Write the format data dict to the frontend. 

169 

170 This default version of this method simply writes the plain text 

171 representation of the object to ``sys.stdout``. Subclasses should 

172 override this method to send the entire `format_dict` to the 

173 frontends. 

174 

175 Parameters 

176 ---------- 

177 format_dict : dict 

178 The format dict for the object passed to `sys.displayhook`. 

179 md_dict : dict (optional) 

180 The metadata dict to be associated with the display data. 

181 """ 

182 if 'text/plain' not in format_dict: 

183 # nothing to do 

184 return 

185 # We want to print because we want to always make sure we have a 

186 # newline, even if all the prompt separators are ''. This is the 

187 # standard IPython behavior. 

188 result_repr = format_dict['text/plain'] 

189 if '\n' in result_repr: 

190 # So that multi-line strings line up with the left column of 

191 # the screen, instead of having the output prompt mess up 

192 # their first line. 

193 # We use the prompt template instead of the expanded prompt 

194 # because the expansion may add ANSI escapes that will interfere 

195 # with our ability to determine whether or not we should add 

196 # a newline. 

197 if not self.prompt_end_newline: 

198 # But avoid extraneous empty lines. 

199 result_repr = '\n' + result_repr 

200 

201 try: 

202 print(result_repr) 

203 except UnicodeEncodeError: 

204 # If a character is not supported by the terminal encoding replace 

205 # it with its \u or \x representation 

206 print(result_repr.encode(sys.stdout.encoding,'backslashreplace').decode(sys.stdout.encoding)) 

207 

208 def update_user_ns(self, result): 

209 """Update user_ns with various things like _, __, _1, etc.""" 

210 

211 # Avoid recursive reference when displaying _oh/Out 

212 if self.cache_size and result is not self.shell.user_ns['_oh']: 

213 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: 

214 self.cull_cache() 

215 

216 # Don't overwrite '_' and friends if '_' is in __builtin__ 

217 # (otherwise we cause buggy behavior for things like gettext). and 

218 # do not overwrite _, __ or ___ if one of these has been assigned 

219 # by the user. 

220 update_unders = True 

221 for unders in ['_'*i for i in range(1,4)]: 

222 if unders not in self.shell.user_ns: 

223 continue 

224 if getattr(self, unders) is not self.shell.user_ns.get(unders): 

225 update_unders = False 

226 

227 self.___ = self.__ 

228 self.__ = self._ 

229 self._ = result 

230 

231 if ('_' not in builtin_mod.__dict__) and (update_unders): 

232 self.shell.push({'_':self._, 

233 '__':self.__, 

234 '___':self.___}, interactive=False) 

235 

236 # hackish access to top-level namespace to create _1,_2... dynamically 

237 to_main = {} 

238 if self.do_full_cache: 

239 new_result = '_%s' % self.prompt_count 

240 to_main[new_result] = result 

241 self.shell.push(to_main, interactive=False) 

242 self.shell.user_ns['_oh'][self.prompt_count] = result 

243 

244 def fill_exec_result(self, result): 

245 if self.exec_result is not None: 

246 self.exec_result.result = result 

247 

248 def log_output(self, format_dict): 

249 """Log the output.""" 

250 from .history import HistoryOutput 

251 self.shell.history_manager.outputs[self.prompt_count].append( 

252 HistoryOutput(output_type="execute_result", bundle=format_dict) 

253 ) 

254 if "text/plain" not in format_dict: 

255 # nothing to do 

256 return 

257 if self.shell.logger.log_output: 

258 self.shell.logger.log_write(format_dict['text/plain'], 'output') 

259 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ 

260 format_dict['text/plain'] 

261 

262 def finish_displayhook(self): 

263 """Finish up all displayhook activities.""" 

264 sys.stdout.write(self.shell.separate_out2) 

265 sys.stdout.flush() 

266 self._is_active = False 

267 

268 def __call__(self, result=None): 

269 """Printing with history cache management. 

270 

271 This is invoked every time the interpreter needs to print, and is 

272 activated by setting the variable sys.displayhook to it. 

273 """ 

274 self.check_for_underscore() 

275 if result is not None and not self.quiet(): 

276 self.start_displayhook() 

277 self.write_output_prompt() 

278 format_dict, md_dict = self.compute_format_data(result) 

279 self.update_user_ns(result) 

280 self.fill_exec_result(result) 

281 if format_dict: 

282 self.write_format_data(format_dict, md_dict) 

283 self.log_output(format_dict) 

284 self.finish_displayhook() 

285 

286 def cull_cache(self): 

287 """Output cache is full, cull the oldest entries""" 

288 oh = self.shell.user_ns.get('_oh', {}) 

289 sz = len(oh) 

290 cull_count = max(int(sz * self.cull_fraction), 2) 

291 warn('Output cache limit (currently {sz} entries) hit.\n' 

292 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count)) 

293 

294 for i, n in enumerate(sorted(oh)): 

295 if i >= cull_count: 

296 break 

297 self.shell.user_ns.pop('_%i' % n, None) 

298 oh.pop(n, None) 

299 

300 def flush(self): 

301 if not self.do_full_cache: 

302 raise ValueError("You shouldn't have reached the cache flush " 

303 "if full caching is not enabled!") 

304 # delete auto-generated vars from global namespace 

305 

306 for n in range(1,self.prompt_count + 1): 

307 key = '_'+repr(n) 

308 try: 

309 del self.shell.user_ns_hidden[key] 

310 except KeyError: 

311 pass 

312 try: 

313 del self.shell.user_ns[key] 

314 except KeyError: 

315 pass 

316 # In some embedded circumstances, the user_ns doesn't have the 

317 # '_oh' key set up. 

318 oh = self.shell.user_ns.get('_oh', None) 

319 if oh is not None: 

320 oh.clear() 

321 

322 # Release our own references to objects: 

323 self._, self.__, self.___ = '', '', '' 

324 

325 if '_' not in builtin_mod.__dict__: 

326 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) 

327 import gc 

328 # TODO: Is this really needed? 

329 # IronPython blocks here forever 

330 if sys.platform != "cli": 

331 gc.collect() 

332 

333 

334class CapturingDisplayHook: 

335 def __init__(self, shell, outputs=None): 

336 self.shell = shell 

337 if outputs is None: 

338 outputs = [] 

339 self.outputs = outputs 

340 

341 def __call__(self, result=None): 

342 if result is None: 

343 return 

344 format_dict, md_dict = self.shell.display_formatter.format(result) 

345 self.outputs.append({ 'data': format_dict, 'metadata': md_dict })