Show More
@@ -1,944 +1,937 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Top-level display functions for displaying object in different formats. |
|
3 | 3 | |
|
4 | 4 | Authors: |
|
5 | 5 | |
|
6 | 6 | * Brian Granger |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2013 The IPython Development Team |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 13 | # the file COPYING, distributed as part of this software. |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Imports |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | from __future__ import print_function |
|
21 | 21 | |
|
22 | 22 | import os |
|
23 | 23 | import struct |
|
24 | 24 | import mimetypes |
|
25 | 25 | |
|
26 | 26 | from IPython.core.formatters import _safe_get_formatter_method |
|
27 | 27 | from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, |
|
28 | 28 | unicode_type) |
|
29 | 29 | from IPython.testing.skipdoctest import skip_doctest |
|
30 | 30 | |
|
31 | 31 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', |
|
32 | 32 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', |
|
33 | 33 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', |
|
34 | 34 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript', |
|
35 | 35 | 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close', |
|
36 | 36 | 'publish_display_data'] |
|
37 | 37 | |
|
38 | 38 | #----------------------------------------------------------------------------- |
|
39 | 39 | # utility functions |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | |
|
42 | 42 | def _safe_exists(path): |
|
43 | 43 | """Check path, but don't let exceptions raise""" |
|
44 | 44 | try: |
|
45 | 45 | return os.path.exists(path) |
|
46 | 46 | except Exception: |
|
47 | 47 | return False |
|
48 | 48 | |
|
49 | 49 | def _merge(d1, d2): |
|
50 | 50 | """Like update, but merges sub-dicts instead of clobbering at the top level. |
|
51 | 51 | |
|
52 | 52 | Updates d1 in-place |
|
53 | 53 | """ |
|
54 | 54 | |
|
55 | 55 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
56 | 56 | return d2 |
|
57 | 57 | for key, value in d2.items(): |
|
58 | 58 | d1[key] = _merge(d1.get(key), value) |
|
59 | 59 | return d1 |
|
60 | 60 | |
|
61 | 61 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
62 | 62 | """internal implementation of all display_foo methods |
|
63 | 63 | |
|
64 | 64 | Parameters |
|
65 | 65 | ---------- |
|
66 | 66 | mimetype : str |
|
67 | 67 | The mimetype to be published (e.g. 'image/png') |
|
68 | 68 | objs : tuple of objects |
|
69 | 69 | The Python objects to display, or if raw=True raw text data to |
|
70 | 70 | display. |
|
71 | 71 | raw : bool |
|
72 | 72 | Are the data objects raw data or Python objects that need to be |
|
73 | 73 | formatted before display? [default: False] |
|
74 | 74 | metadata : dict (optional) |
|
75 | 75 | Metadata to be associated with the specific mimetype output. |
|
76 | 76 | """ |
|
77 | 77 | if metadata: |
|
78 | 78 | metadata = {mimetype: metadata} |
|
79 | 79 | if raw: |
|
80 | 80 | # turn list of pngdata into list of { 'image/png': pngdata } |
|
81 | 81 | objs = [ {mimetype: obj} for obj in objs ] |
|
82 | 82 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) |
|
83 | 83 | |
|
84 | 84 | #----------------------------------------------------------------------------- |
|
85 | 85 | # Main functions |
|
86 | 86 | #----------------------------------------------------------------------------- |
|
87 | 87 | |
|
88 | 88 | def publish_display_data(data, metadata=None, source=None): |
|
89 | 89 | """Publish data and metadata to all frontends. |
|
90 | 90 | |
|
91 | 91 | See the ``display_data`` message in the messaging documentation for |
|
92 | 92 | more details about this message type. |
|
93 | 93 | |
|
94 | 94 | The following MIME types are currently implemented: |
|
95 | 95 | |
|
96 | 96 | * text/plain |
|
97 | 97 | * text/html |
|
98 | 98 | * text/markdown |
|
99 | 99 | * text/latex |
|
100 | 100 | * application/json |
|
101 | 101 | * application/javascript |
|
102 | 102 | * image/png |
|
103 | 103 | * image/jpeg |
|
104 | 104 | * image/svg+xml |
|
105 | 105 | |
|
106 | 106 | Parameters |
|
107 | 107 | ---------- |
|
108 | 108 | data : dict |
|
109 | 109 | A dictionary having keys that are valid MIME types (like |
|
110 | 110 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
111 | 111 | that MIME type. The data itself must be a JSON'able data |
|
112 | 112 | structure. Minimally all data should have the 'text/plain' data, |
|
113 | 113 | which can be displayed by all frontends. If more than the plain |
|
114 | 114 | text is given, it is up to the frontend to decide which |
|
115 | 115 | representation to use. |
|
116 | 116 | metadata : dict |
|
117 | 117 | A dictionary for metadata related to the data. This can contain |
|
118 | 118 | arbitrary key, value pairs that frontends can use to interpret |
|
119 | 119 | the data. mime-type keys matching those in data can be used |
|
120 | 120 | to specify metadata about particular representations. |
|
121 | 121 | source : str, deprecated |
|
122 | 122 | Unused. |
|
123 | 123 | """ |
|
124 | 124 | from IPython.core.interactiveshell import InteractiveShell |
|
125 | 125 | InteractiveShell.instance().display_pub.publish( |
|
126 | 126 | data=data, |
|
127 | 127 | metadata=metadata, |
|
128 | 128 | ) |
|
129 | 129 | |
|
130 | 130 | def display(*objs, **kwargs): |
|
131 | 131 | """Display a Python object in all frontends. |
|
132 | 132 | |
|
133 | 133 | By default all representations will be computed and sent to the frontends. |
|
134 | 134 | Frontends can decide which representation is used and how. |
|
135 | 135 | |
|
136 | 136 | Parameters |
|
137 | 137 | ---------- |
|
138 | 138 | objs : tuple of objects |
|
139 | 139 | The Python objects to display. |
|
140 | 140 | raw : bool, optional |
|
141 | 141 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
142 | 142 | or Python objects that need to be formatted before display? [default: False] |
|
143 | 143 | include : list or tuple, optional |
|
144 | 144 | A list of format type strings (MIME types) to include in the |
|
145 | 145 | format data dict. If this is set *only* the format types included |
|
146 | 146 | in this list will be computed. |
|
147 | 147 | exclude : list or tuple, optional |
|
148 | 148 | A list of format type strings (MIME types) to exclude in the format |
|
149 | 149 | data dict. If this is set all format types will be computed, |
|
150 | 150 | except for those included in this argument. |
|
151 | 151 | metadata : dict, optional |
|
152 | 152 | A dictionary of metadata to associate with the output. |
|
153 | 153 | mime-type keys in this dictionary will be associated with the individual |
|
154 | 154 | representation formats, if they exist. |
|
155 | 155 | """ |
|
156 | 156 | raw = kwargs.get('raw', False) |
|
157 | 157 | include = kwargs.get('include') |
|
158 | 158 | exclude = kwargs.get('exclude') |
|
159 | 159 | metadata = kwargs.get('metadata') |
|
160 | 160 | |
|
161 | 161 | from IPython.core.interactiveshell import InteractiveShell |
|
162 | 162 | |
|
163 | 163 | if not raw: |
|
164 | 164 | format = InteractiveShell.instance().display_formatter.format |
|
165 | 165 | |
|
166 | 166 | for obj in objs: |
|
167 | ||
|
168 | # If _ipython_display_ is defined, use that to display this object. | |
|
169 | display_method = _safe_get_formatter_method(obj, '_ipython_display_') | |
|
170 | if display_method is not None: | |
|
171 | try: | |
|
172 | display_method(**kwargs) | |
|
173 | except NotImplementedError: | |
|
174 | pass | |
|
175 | else: | |
|
176 | continue | |
|
177 | 167 | if raw: |
|
178 | 168 | publish_display_data(data=obj, metadata=metadata) |
|
179 | 169 | else: |
|
180 | 170 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
171 | if not format_dict: | |
|
172 | # nothing to display (e.g. _ipython_display_ took over) | |
|
173 | continue | |
|
181 | 174 | if metadata: |
|
182 | 175 | # kwarg-specified metadata gets precedence |
|
183 | 176 | _merge(md_dict, metadata) |
|
184 | 177 | publish_display_data(data=format_dict, metadata=md_dict) |
|
185 | 178 | |
|
186 | 179 | |
|
187 | 180 | def display_pretty(*objs, **kwargs): |
|
188 | 181 | """Display the pretty (default) representation of an object. |
|
189 | 182 | |
|
190 | 183 | Parameters |
|
191 | 184 | ---------- |
|
192 | 185 | objs : tuple of objects |
|
193 | 186 | The Python objects to display, or if raw=True raw text data to |
|
194 | 187 | display. |
|
195 | 188 | raw : bool |
|
196 | 189 | Are the data objects raw data or Python objects that need to be |
|
197 | 190 | formatted before display? [default: False] |
|
198 | 191 | metadata : dict (optional) |
|
199 | 192 | Metadata to be associated with the specific mimetype output. |
|
200 | 193 | """ |
|
201 | 194 | _display_mimetype('text/plain', objs, **kwargs) |
|
202 | 195 | |
|
203 | 196 | |
|
204 | 197 | def display_html(*objs, **kwargs): |
|
205 | 198 | """Display the HTML representation of an object. |
|
206 | 199 | |
|
207 | 200 | Parameters |
|
208 | 201 | ---------- |
|
209 | 202 | objs : tuple of objects |
|
210 | 203 | The Python objects to display, or if raw=True raw HTML data to |
|
211 | 204 | display. |
|
212 | 205 | raw : bool |
|
213 | 206 | Are the data objects raw data or Python objects that need to be |
|
214 | 207 | formatted before display? [default: False] |
|
215 | 208 | metadata : dict (optional) |
|
216 | 209 | Metadata to be associated with the specific mimetype output. |
|
217 | 210 | """ |
|
218 | 211 | _display_mimetype('text/html', objs, **kwargs) |
|
219 | 212 | |
|
220 | 213 | |
|
221 | 214 | def display_markdown(*objs, **kwargs): |
|
222 | 215 | """Displays the Markdown representation of an object. |
|
223 | 216 | |
|
224 | 217 | Parameters |
|
225 | 218 | ---------- |
|
226 | 219 | objs : tuple of objects |
|
227 | 220 | The Python objects to display, or if raw=True raw markdown data to |
|
228 | 221 | display. |
|
229 | 222 | raw : bool |
|
230 | 223 | Are the data objects raw data or Python objects that need to be |
|
231 | 224 | formatted before display? [default: False] |
|
232 | 225 | metadata : dict (optional) |
|
233 | 226 | Metadata to be associated with the specific mimetype output. |
|
234 | 227 | """ |
|
235 | 228 | |
|
236 | 229 | _display_mimetype('text/markdown', objs, **kwargs) |
|
237 | 230 | |
|
238 | 231 | |
|
239 | 232 | def display_svg(*objs, **kwargs): |
|
240 | 233 | """Display the SVG representation of an object. |
|
241 | 234 | |
|
242 | 235 | Parameters |
|
243 | 236 | ---------- |
|
244 | 237 | objs : tuple of objects |
|
245 | 238 | The Python objects to display, or if raw=True raw svg data to |
|
246 | 239 | display. |
|
247 | 240 | raw : bool |
|
248 | 241 | Are the data objects raw data or Python objects that need to be |
|
249 | 242 | formatted before display? [default: False] |
|
250 | 243 | metadata : dict (optional) |
|
251 | 244 | Metadata to be associated with the specific mimetype output. |
|
252 | 245 | """ |
|
253 | 246 | _display_mimetype('image/svg+xml', objs, **kwargs) |
|
254 | 247 | |
|
255 | 248 | |
|
256 | 249 | def display_png(*objs, **kwargs): |
|
257 | 250 | """Display the PNG representation of an object. |
|
258 | 251 | |
|
259 | 252 | Parameters |
|
260 | 253 | ---------- |
|
261 | 254 | objs : tuple of objects |
|
262 | 255 | The Python objects to display, or if raw=True raw png data to |
|
263 | 256 | display. |
|
264 | 257 | raw : bool |
|
265 | 258 | Are the data objects raw data or Python objects that need to be |
|
266 | 259 | formatted before display? [default: False] |
|
267 | 260 | metadata : dict (optional) |
|
268 | 261 | Metadata to be associated with the specific mimetype output. |
|
269 | 262 | """ |
|
270 | 263 | _display_mimetype('image/png', objs, **kwargs) |
|
271 | 264 | |
|
272 | 265 | |
|
273 | 266 | def display_jpeg(*objs, **kwargs): |
|
274 | 267 | """Display the JPEG representation of an object. |
|
275 | 268 | |
|
276 | 269 | Parameters |
|
277 | 270 | ---------- |
|
278 | 271 | objs : tuple of objects |
|
279 | 272 | The Python objects to display, or if raw=True raw JPEG data to |
|
280 | 273 | display. |
|
281 | 274 | raw : bool |
|
282 | 275 | Are the data objects raw data or Python objects that need to be |
|
283 | 276 | formatted before display? [default: False] |
|
284 | 277 | metadata : dict (optional) |
|
285 | 278 | Metadata to be associated with the specific mimetype output. |
|
286 | 279 | """ |
|
287 | 280 | _display_mimetype('image/jpeg', objs, **kwargs) |
|
288 | 281 | |
|
289 | 282 | |
|
290 | 283 | def display_latex(*objs, **kwargs): |
|
291 | 284 | """Display the LaTeX representation of an object. |
|
292 | 285 | |
|
293 | 286 | Parameters |
|
294 | 287 | ---------- |
|
295 | 288 | objs : tuple of objects |
|
296 | 289 | The Python objects to display, or if raw=True raw latex data to |
|
297 | 290 | display. |
|
298 | 291 | raw : bool |
|
299 | 292 | Are the data objects raw data or Python objects that need to be |
|
300 | 293 | formatted before display? [default: False] |
|
301 | 294 | metadata : dict (optional) |
|
302 | 295 | Metadata to be associated with the specific mimetype output. |
|
303 | 296 | """ |
|
304 | 297 | _display_mimetype('text/latex', objs, **kwargs) |
|
305 | 298 | |
|
306 | 299 | |
|
307 | 300 | def display_json(*objs, **kwargs): |
|
308 | 301 | """Display the JSON representation of an object. |
|
309 | 302 | |
|
310 | 303 | Note that not many frontends support displaying JSON. |
|
311 | 304 | |
|
312 | 305 | Parameters |
|
313 | 306 | ---------- |
|
314 | 307 | objs : tuple of objects |
|
315 | 308 | The Python objects to display, or if raw=True raw json data to |
|
316 | 309 | display. |
|
317 | 310 | raw : bool |
|
318 | 311 | Are the data objects raw data or Python objects that need to be |
|
319 | 312 | formatted before display? [default: False] |
|
320 | 313 | metadata : dict (optional) |
|
321 | 314 | Metadata to be associated with the specific mimetype output. |
|
322 | 315 | """ |
|
323 | 316 | _display_mimetype('application/json', objs, **kwargs) |
|
324 | 317 | |
|
325 | 318 | |
|
326 | 319 | def display_javascript(*objs, **kwargs): |
|
327 | 320 | """Display the Javascript representation of an object. |
|
328 | 321 | |
|
329 | 322 | Parameters |
|
330 | 323 | ---------- |
|
331 | 324 | objs : tuple of objects |
|
332 | 325 | The Python objects to display, or if raw=True raw javascript data to |
|
333 | 326 | display. |
|
334 | 327 | raw : bool |
|
335 | 328 | Are the data objects raw data or Python objects that need to be |
|
336 | 329 | formatted before display? [default: False] |
|
337 | 330 | metadata : dict (optional) |
|
338 | 331 | Metadata to be associated with the specific mimetype output. |
|
339 | 332 | """ |
|
340 | 333 | _display_mimetype('application/javascript', objs, **kwargs) |
|
341 | 334 | |
|
342 | 335 | |
|
343 | 336 | def display_pdf(*objs, **kwargs): |
|
344 | 337 | """Display the PDF representation of an object. |
|
345 | 338 | |
|
346 | 339 | Parameters |
|
347 | 340 | ---------- |
|
348 | 341 | objs : tuple of objects |
|
349 | 342 | The Python objects to display, or if raw=True raw javascript data to |
|
350 | 343 | display. |
|
351 | 344 | raw : bool |
|
352 | 345 | Are the data objects raw data or Python objects that need to be |
|
353 | 346 | formatted before display? [default: False] |
|
354 | 347 | metadata : dict (optional) |
|
355 | 348 | Metadata to be associated with the specific mimetype output. |
|
356 | 349 | """ |
|
357 | 350 | _display_mimetype('application/pdf', objs, **kwargs) |
|
358 | 351 | |
|
359 | 352 | |
|
360 | 353 | #----------------------------------------------------------------------------- |
|
361 | 354 | # Smart classes |
|
362 | 355 | #----------------------------------------------------------------------------- |
|
363 | 356 | |
|
364 | 357 | |
|
365 | 358 | class DisplayObject(object): |
|
366 | 359 | """An object that wraps data to be displayed.""" |
|
367 | 360 | |
|
368 | 361 | _read_flags = 'r' |
|
369 | 362 | _show_mem_addr = False |
|
370 | 363 | |
|
371 | 364 | def __init__(self, data=None, url=None, filename=None): |
|
372 | 365 | """Create a display object given raw data. |
|
373 | 366 | |
|
374 | 367 | When this object is returned by an expression or passed to the |
|
375 | 368 | display function, it will result in the data being displayed |
|
376 | 369 | in the frontend. The MIME type of the data should match the |
|
377 | 370 | subclasses used, so the Png subclass should be used for 'image/png' |
|
378 | 371 | data. If the data is a URL, the data will first be downloaded |
|
379 | 372 | and then displayed. If |
|
380 | 373 | |
|
381 | 374 | Parameters |
|
382 | 375 | ---------- |
|
383 | 376 | data : unicode, str or bytes |
|
384 | 377 | The raw data or a URL or file to load the data from |
|
385 | 378 | url : unicode |
|
386 | 379 | A URL to download the data from. |
|
387 | 380 | filename : unicode |
|
388 | 381 | Path to a local file to load the data from. |
|
389 | 382 | """ |
|
390 | 383 | if data is not None and isinstance(data, string_types): |
|
391 | 384 | if data.startswith('http') and url is None: |
|
392 | 385 | url = data |
|
393 | 386 | filename = None |
|
394 | 387 | data = None |
|
395 | 388 | elif _safe_exists(data) and filename is None: |
|
396 | 389 | url = None |
|
397 | 390 | filename = data |
|
398 | 391 | data = None |
|
399 | 392 | |
|
400 | 393 | self.data = data |
|
401 | 394 | self.url = url |
|
402 | 395 | self.filename = None if filename is None else unicode_type(filename) |
|
403 | 396 | |
|
404 | 397 | self.reload() |
|
405 | 398 | self._check_data() |
|
406 | 399 | |
|
407 | 400 | def __repr__(self): |
|
408 | 401 | if not self._show_mem_addr: |
|
409 | 402 | cls = self.__class__ |
|
410 | 403 | r = "<%s.%s object>" % (cls.__module__, cls.__name__) |
|
411 | 404 | else: |
|
412 | 405 | r = super(DisplayObject, self).__repr__() |
|
413 | 406 | return r |
|
414 | 407 | |
|
415 | 408 | def _check_data(self): |
|
416 | 409 | """Override in subclasses if there's something to check.""" |
|
417 | 410 | pass |
|
418 | 411 | |
|
419 | 412 | def reload(self): |
|
420 | 413 | """Reload the raw data from file or URL.""" |
|
421 | 414 | if self.filename is not None: |
|
422 | 415 | with open(self.filename, self._read_flags) as f: |
|
423 | 416 | self.data = f.read() |
|
424 | 417 | elif self.url is not None: |
|
425 | 418 | try: |
|
426 | 419 | try: |
|
427 | 420 | from urllib.request import urlopen # Py3 |
|
428 | 421 | except ImportError: |
|
429 | 422 | from urllib2 import urlopen |
|
430 | 423 | response = urlopen(self.url) |
|
431 | 424 | self.data = response.read() |
|
432 | 425 | # extract encoding from header, if there is one: |
|
433 | 426 | encoding = None |
|
434 | 427 | for sub in response.headers['content-type'].split(';'): |
|
435 | 428 | sub = sub.strip() |
|
436 | 429 | if sub.startswith('charset'): |
|
437 | 430 | encoding = sub.split('=')[-1].strip() |
|
438 | 431 | break |
|
439 | 432 | # decode data, if an encoding was specified |
|
440 | 433 | if encoding: |
|
441 | 434 | self.data = self.data.decode(encoding, 'replace') |
|
442 | 435 | except: |
|
443 | 436 | self.data = None |
|
444 | 437 | |
|
445 | 438 | class TextDisplayObject(DisplayObject): |
|
446 | 439 | """Validate that display data is text""" |
|
447 | 440 | def _check_data(self): |
|
448 | 441 | if self.data is not None and not isinstance(self.data, string_types): |
|
449 | 442 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) |
|
450 | 443 | |
|
451 | 444 | class Pretty(TextDisplayObject): |
|
452 | 445 | |
|
453 | 446 | def _repr_pretty_(self): |
|
454 | 447 | return self.data |
|
455 | 448 | |
|
456 | 449 | |
|
457 | 450 | class HTML(TextDisplayObject): |
|
458 | 451 | |
|
459 | 452 | def _repr_html_(self): |
|
460 | 453 | return self.data |
|
461 | 454 | |
|
462 | 455 | def __html__(self): |
|
463 | 456 | """ |
|
464 | 457 | This method exists to inform other HTML-using modules (e.g. Markupsafe, |
|
465 | 458 | htmltag, etc) that this object is HTML and does not need things like |
|
466 | 459 | special characters (<>&) escaped. |
|
467 | 460 | """ |
|
468 | 461 | return self._repr_html_() |
|
469 | 462 | |
|
470 | 463 | |
|
471 | 464 | class Markdown(TextDisplayObject): |
|
472 | 465 | |
|
473 | 466 | def _repr_markdown_(self): |
|
474 | 467 | return self.data |
|
475 | 468 | |
|
476 | 469 | |
|
477 | 470 | class Math(TextDisplayObject): |
|
478 | 471 | |
|
479 | 472 | def _repr_latex_(self): |
|
480 | 473 | s = self.data.strip('$') |
|
481 | 474 | return "$$%s$$" % s |
|
482 | 475 | |
|
483 | 476 | |
|
484 | 477 | class Latex(TextDisplayObject): |
|
485 | 478 | |
|
486 | 479 | def _repr_latex_(self): |
|
487 | 480 | return self.data |
|
488 | 481 | |
|
489 | 482 | |
|
490 | 483 | class SVG(DisplayObject): |
|
491 | 484 | |
|
492 | 485 | # wrap data in a property, which extracts the <svg> tag, discarding |
|
493 | 486 | # document headers |
|
494 | 487 | _data = None |
|
495 | 488 | |
|
496 | 489 | @property |
|
497 | 490 | def data(self): |
|
498 | 491 | return self._data |
|
499 | 492 | |
|
500 | 493 | @data.setter |
|
501 | 494 | def data(self, svg): |
|
502 | 495 | if svg is None: |
|
503 | 496 | self._data = None |
|
504 | 497 | return |
|
505 | 498 | # parse into dom object |
|
506 | 499 | from xml.dom import minidom |
|
507 | 500 | svg = cast_bytes_py2(svg) |
|
508 | 501 | x = minidom.parseString(svg) |
|
509 | 502 | # get svg tag (should be 1) |
|
510 | 503 | found_svg = x.getElementsByTagName('svg') |
|
511 | 504 | if found_svg: |
|
512 | 505 | svg = found_svg[0].toxml() |
|
513 | 506 | else: |
|
514 | 507 | # fallback on the input, trust the user |
|
515 | 508 | # but this is probably an error. |
|
516 | 509 | pass |
|
517 | 510 | svg = cast_unicode(svg) |
|
518 | 511 | self._data = svg |
|
519 | 512 | |
|
520 | 513 | def _repr_svg_(self): |
|
521 | 514 | return self.data |
|
522 | 515 | |
|
523 | 516 | |
|
524 | 517 | class JSON(TextDisplayObject): |
|
525 | 518 | |
|
526 | 519 | def _repr_json_(self): |
|
527 | 520 | return self.data |
|
528 | 521 | |
|
529 | 522 | css_t = """$("head").append($("<link/>").attr({ |
|
530 | 523 | rel: "stylesheet", |
|
531 | 524 | type: "text/css", |
|
532 | 525 | href: "%s" |
|
533 | 526 | })); |
|
534 | 527 | """ |
|
535 | 528 | |
|
536 | 529 | lib_t1 = """$.getScript("%s", function () { |
|
537 | 530 | """ |
|
538 | 531 | lib_t2 = """}); |
|
539 | 532 | """ |
|
540 | 533 | |
|
541 | 534 | class Javascript(TextDisplayObject): |
|
542 | 535 | |
|
543 | 536 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): |
|
544 | 537 | """Create a Javascript display object given raw data. |
|
545 | 538 | |
|
546 | 539 | When this object is returned by an expression or passed to the |
|
547 | 540 | display function, it will result in the data being displayed |
|
548 | 541 | in the frontend. If the data is a URL, the data will first be |
|
549 | 542 | downloaded and then displayed. |
|
550 | 543 | |
|
551 | 544 | In the Notebook, the containing element will be available as `element`, |
|
552 | 545 | and jQuery will be available. Content appended to `element` will be |
|
553 | 546 | visible in the output area. |
|
554 | 547 | |
|
555 | 548 | Parameters |
|
556 | 549 | ---------- |
|
557 | 550 | data : unicode, str or bytes |
|
558 | 551 | The Javascript source code or a URL to download it from. |
|
559 | 552 | url : unicode |
|
560 | 553 | A URL to download the data from. |
|
561 | 554 | filename : unicode |
|
562 | 555 | Path to a local file to load the data from. |
|
563 | 556 | lib : list or str |
|
564 | 557 | A sequence of Javascript library URLs to load asynchronously before |
|
565 | 558 | running the source code. The full URLs of the libraries should |
|
566 | 559 | be given. A single Javascript library URL can also be given as a |
|
567 | 560 | string. |
|
568 | 561 | css: : list or str |
|
569 | 562 | A sequence of css files to load before running the source code. |
|
570 | 563 | The full URLs of the css files should be given. A single css URL |
|
571 | 564 | can also be given as a string. |
|
572 | 565 | """ |
|
573 | 566 | if isinstance(lib, string_types): |
|
574 | 567 | lib = [lib] |
|
575 | 568 | elif lib is None: |
|
576 | 569 | lib = [] |
|
577 | 570 | if isinstance(css, string_types): |
|
578 | 571 | css = [css] |
|
579 | 572 | elif css is None: |
|
580 | 573 | css = [] |
|
581 | 574 | if not isinstance(lib, (list,tuple)): |
|
582 | 575 | raise TypeError('expected sequence, got: %r' % lib) |
|
583 | 576 | if not isinstance(css, (list,tuple)): |
|
584 | 577 | raise TypeError('expected sequence, got: %r' % css) |
|
585 | 578 | self.lib = lib |
|
586 | 579 | self.css = css |
|
587 | 580 | super(Javascript, self).__init__(data=data, url=url, filename=filename) |
|
588 | 581 | |
|
589 | 582 | def _repr_javascript_(self): |
|
590 | 583 | r = '' |
|
591 | 584 | for c in self.css: |
|
592 | 585 | r += css_t % c |
|
593 | 586 | for l in self.lib: |
|
594 | 587 | r += lib_t1 % l |
|
595 | 588 | r += self.data |
|
596 | 589 | r += lib_t2*len(self.lib) |
|
597 | 590 | return r |
|
598 | 591 | |
|
599 | 592 | # constants for identifying png/jpeg data |
|
600 | 593 | _PNG = b'\x89PNG\r\n\x1a\n' |
|
601 | 594 | _JPEG = b'\xff\xd8' |
|
602 | 595 | |
|
603 | 596 | def _pngxy(data): |
|
604 | 597 | """read the (width, height) from a PNG header""" |
|
605 | 598 | ihdr = data.index(b'IHDR') |
|
606 | 599 | # next 8 bytes are width/height |
|
607 | 600 | w4h4 = data[ihdr+4:ihdr+12] |
|
608 | 601 | return struct.unpack('>ii', w4h4) |
|
609 | 602 | |
|
610 | 603 | def _jpegxy(data): |
|
611 | 604 | """read the (width, height) from a JPEG header""" |
|
612 | 605 | # adapted from http://www.64lines.com/jpeg-width-height |
|
613 | 606 | |
|
614 | 607 | idx = 4 |
|
615 | 608 | while True: |
|
616 | 609 | block_size = struct.unpack('>H', data[idx:idx+2])[0] |
|
617 | 610 | idx = idx + block_size |
|
618 | 611 | if data[idx:idx+2] == b'\xFF\xC0': |
|
619 | 612 | # found Start of Frame |
|
620 | 613 | iSOF = idx |
|
621 | 614 | break |
|
622 | 615 | else: |
|
623 | 616 | # read another block |
|
624 | 617 | idx += 2 |
|
625 | 618 | |
|
626 | 619 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) |
|
627 | 620 | return w, h |
|
628 | 621 | |
|
629 | 622 | class Image(DisplayObject): |
|
630 | 623 | |
|
631 | 624 | _read_flags = 'rb' |
|
632 | 625 | _FMT_JPEG = u'jpeg' |
|
633 | 626 | _FMT_PNG = u'png' |
|
634 | 627 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] |
|
635 | 628 | |
|
636 | 629 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False): |
|
637 | 630 | """Create a PNG/JPEG image object given raw data. |
|
638 | 631 | |
|
639 | 632 | When this object is returned by an input cell or passed to the |
|
640 | 633 | display function, it will result in the image being displayed |
|
641 | 634 | in the frontend. |
|
642 | 635 | |
|
643 | 636 | Parameters |
|
644 | 637 | ---------- |
|
645 | 638 | data : unicode, str or bytes |
|
646 | 639 | The raw image data or a URL or filename to load the data from. |
|
647 | 640 | This always results in embedded image data. |
|
648 | 641 | url : unicode |
|
649 | 642 | A URL to download the data from. If you specify `url=`, |
|
650 | 643 | the image data will not be embedded unless you also specify `embed=True`. |
|
651 | 644 | filename : unicode |
|
652 | 645 | Path to a local file to load the data from. |
|
653 | 646 | Images from a file are always embedded. |
|
654 | 647 | format : unicode |
|
655 | 648 | The format of the image data (png/jpeg/jpg). If a filename or URL is given |
|
656 | 649 | for format will be inferred from the filename extension. |
|
657 | 650 | embed : bool |
|
658 | 651 | Should the image data be embedded using a data URI (True) or be |
|
659 | 652 | loaded using an <img> tag. Set this to True if you want the image |
|
660 | 653 | to be viewable later with no internet connection in the notebook. |
|
661 | 654 | |
|
662 | 655 | Default is `True`, unless the keyword argument `url` is set, then |
|
663 | 656 | default value is `False`. |
|
664 | 657 | |
|
665 | 658 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
666 | 659 | width : int |
|
667 | 660 | Width to which to constrain the image in html |
|
668 | 661 | height : int |
|
669 | 662 | Height to which to constrain the image in html |
|
670 | 663 | retina : bool |
|
671 | 664 | Automatically set the width and height to half of the measured |
|
672 | 665 | width and height. |
|
673 | 666 | This only works for embedded images because it reads the width/height |
|
674 | 667 | from image data. |
|
675 | 668 | For non-embedded images, you can just set the desired display width |
|
676 | 669 | and height directly. |
|
677 | 670 | |
|
678 | 671 | Examples |
|
679 | 672 | -------- |
|
680 | 673 | # embedded image data, works in qtconsole and notebook |
|
681 | 674 | # when passed positionally, the first arg can be any of raw image data, |
|
682 | 675 | # a URL, or a filename from which to load image data. |
|
683 | 676 | # The result is always embedding image data for inline images. |
|
684 | 677 | Image('http://www.google.fr/images/srpr/logo3w.png') |
|
685 | 678 | Image('/path/to/image.jpg') |
|
686 | 679 | Image(b'RAW_PNG_DATA...') |
|
687 | 680 | |
|
688 | 681 | # Specifying Image(url=...) does not embed the image data, |
|
689 | 682 | # it only generates `<img>` tag with a link to the source. |
|
690 | 683 | # This will not work in the qtconsole or offline. |
|
691 | 684 | Image(url='http://www.google.fr/images/srpr/logo3w.png') |
|
692 | 685 | |
|
693 | 686 | """ |
|
694 | 687 | if filename is not None: |
|
695 | 688 | ext = self._find_ext(filename) |
|
696 | 689 | elif url is not None: |
|
697 | 690 | ext = self._find_ext(url) |
|
698 | 691 | elif data is None: |
|
699 | 692 | raise ValueError("No image data found. Expecting filename, url, or data.") |
|
700 | 693 | elif isinstance(data, string_types) and ( |
|
701 | 694 | data.startswith('http') or _safe_exists(data) |
|
702 | 695 | ): |
|
703 | 696 | ext = self._find_ext(data) |
|
704 | 697 | else: |
|
705 | 698 | ext = None |
|
706 | 699 | |
|
707 | 700 | if ext is not None: |
|
708 | 701 | format = ext.lower() |
|
709 | 702 | if ext == u'jpg' or ext == u'jpeg': |
|
710 | 703 | format = self._FMT_JPEG |
|
711 | 704 | if ext == u'png': |
|
712 | 705 | format = self._FMT_PNG |
|
713 | 706 | elif isinstance(data, bytes) and format == 'png': |
|
714 | 707 | # infer image type from image data header, |
|
715 | 708 | # only if format might not have been specified. |
|
716 | 709 | if data[:2] == _JPEG: |
|
717 | 710 | format = 'jpeg' |
|
718 | 711 | |
|
719 | 712 | self.format = unicode_type(format).lower() |
|
720 | 713 | self.embed = embed if embed is not None else (url is None) |
|
721 | 714 | |
|
722 | 715 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: |
|
723 | 716 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) |
|
724 | 717 | self.width = width |
|
725 | 718 | self.height = height |
|
726 | 719 | self.retina = retina |
|
727 | 720 | super(Image, self).__init__(data=data, url=url, filename=filename) |
|
728 | 721 | |
|
729 | 722 | if retina: |
|
730 | 723 | self._retina_shape() |
|
731 | 724 | |
|
732 | 725 | def _retina_shape(self): |
|
733 | 726 | """load pixel-doubled width and height from image data""" |
|
734 | 727 | if not self.embed: |
|
735 | 728 | return |
|
736 | 729 | if self.format == 'png': |
|
737 | 730 | w, h = _pngxy(self.data) |
|
738 | 731 | elif self.format == 'jpeg': |
|
739 | 732 | w, h = _jpegxy(self.data) |
|
740 | 733 | else: |
|
741 | 734 | # retina only supports png |
|
742 | 735 | return |
|
743 | 736 | self.width = w // 2 |
|
744 | 737 | self.height = h // 2 |
|
745 | 738 | |
|
746 | 739 | def reload(self): |
|
747 | 740 | """Reload the raw data from file or URL.""" |
|
748 | 741 | if self.embed: |
|
749 | 742 | super(Image,self).reload() |
|
750 | 743 | if self.retina: |
|
751 | 744 | self._retina_shape() |
|
752 | 745 | |
|
753 | 746 | def _repr_html_(self): |
|
754 | 747 | if not self.embed: |
|
755 | 748 | width = height = '' |
|
756 | 749 | if self.width: |
|
757 | 750 | width = ' width="%d"' % self.width |
|
758 | 751 | if self.height: |
|
759 | 752 | height = ' height="%d"' % self.height |
|
760 | 753 | return u'<img src="%s"%s%s/>' % (self.url, width, height) |
|
761 | 754 | |
|
762 | 755 | def _data_and_metadata(self): |
|
763 | 756 | """shortcut for returning metadata with shape information, if defined""" |
|
764 | 757 | md = {} |
|
765 | 758 | if self.width: |
|
766 | 759 | md['width'] = self.width |
|
767 | 760 | if self.height: |
|
768 | 761 | md['height'] = self.height |
|
769 | 762 | if md: |
|
770 | 763 | return self.data, md |
|
771 | 764 | else: |
|
772 | 765 | return self.data |
|
773 | 766 | |
|
774 | 767 | def _repr_png_(self): |
|
775 | 768 | if self.embed and self.format == u'png': |
|
776 | 769 | return self._data_and_metadata() |
|
777 | 770 | |
|
778 | 771 | def _repr_jpeg_(self): |
|
779 | 772 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): |
|
780 | 773 | return self._data_and_metadata() |
|
781 | 774 | |
|
782 | 775 | def _find_ext(self, s): |
|
783 | 776 | return unicode_type(s.split('.')[-1].lower()) |
|
784 | 777 | |
|
785 | 778 | class Video(DisplayObject): |
|
786 | 779 | |
|
787 | 780 | def __init__(self, data=None, url=None, filename=None, embed=None, mimetype=None): |
|
788 | 781 | """Create a video object given raw data or an URL. |
|
789 | 782 | |
|
790 | 783 | When this object is returned by an input cell or passed to the |
|
791 | 784 | display function, it will result in the video being displayed |
|
792 | 785 | in the frontend. |
|
793 | 786 | |
|
794 | 787 | Parameters |
|
795 | 788 | ---------- |
|
796 | 789 | data : unicode, str or bytes |
|
797 | 790 | The raw image data or a URL or filename to load the data from. |
|
798 | 791 | This always results in embedded image data. |
|
799 | 792 | url : unicode |
|
800 | 793 | A URL to download the data from. If you specify `url=`, |
|
801 | 794 | the image data will not be embedded unless you also specify `embed=True`. |
|
802 | 795 | filename : unicode |
|
803 | 796 | Path to a local file to load the data from. |
|
804 | 797 | Videos from a file are always embedded. |
|
805 | 798 | embed : bool |
|
806 | 799 | Should the image data be embedded using a data URI (True) or be |
|
807 | 800 | loaded using an <img> tag. Set this to True if you want the image |
|
808 | 801 | to be viewable later with no internet connection in the notebook. |
|
809 | 802 | |
|
810 | 803 | Default is `True`, unless the keyword argument `url` is set, then |
|
811 | 804 | default value is `False`. |
|
812 | 805 | |
|
813 | 806 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
814 | 807 | mimetype: unicode |
|
815 | 808 | Specify the mimetype in case you load in a encoded video. |
|
816 | 809 | Examples |
|
817 | 810 | -------- |
|
818 | 811 | Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') |
|
819 | 812 | Video('path/to/video.mp4') |
|
820 | 813 | Video('path/to/video.mp4', embed=False) |
|
821 | 814 | """ |
|
822 | 815 | if url is None and (data.startswith('http') or data.startswith('https')): |
|
823 | 816 | url = data |
|
824 | 817 | data = None |
|
825 | 818 | embed = False |
|
826 | 819 | elif os.path.exists(data): |
|
827 | 820 | filename = data |
|
828 | 821 | data = None |
|
829 | 822 | |
|
830 | 823 | self.mimetype = mimetype |
|
831 | 824 | self.embed = embed if embed is not None else (filename is not None) |
|
832 | 825 | super(Video, self).__init__(data=data, url=url, filename=filename) |
|
833 | 826 | |
|
834 | 827 | def _repr_html_(self): |
|
835 | 828 | # External URLs and potentially local files are not embedded into the |
|
836 | 829 | # notebook output. |
|
837 | 830 | if not self.embed: |
|
838 | 831 | url = self.url if self.url is not None else self.filename |
|
839 | 832 | output = """<video src="{0}" controls> |
|
840 | 833 | Your browser does not support the <code>video</code> element. |
|
841 | 834 | </video>""".format(url) |
|
842 | 835 | return output |
|
843 | 836 | # Embedded videos uses base64 encoded videos. |
|
844 | 837 | if self.filename is not None: |
|
845 | 838 | mimetypes.init() |
|
846 | 839 | mimetype, encoding = mimetypes.guess_type(self.filename) |
|
847 | 840 | |
|
848 | 841 | video = open(self.filename, 'rb').read() |
|
849 | 842 | video_encoded = video.encode('base64') |
|
850 | 843 | else: |
|
851 | 844 | video_encoded = self.data |
|
852 | 845 | mimetype = self.mimetype |
|
853 | 846 | output = """<video controls> |
|
854 | 847 | <source src="data:{0};base64,{1}" type="{0}"> |
|
855 | 848 | Your browser does not support the video tag. |
|
856 | 849 | </video>""".format(mimetype, video_encoded) |
|
857 | 850 | return output |
|
858 | 851 | |
|
859 | 852 | def reload(self): |
|
860 | 853 | # TODO |
|
861 | 854 | pass |
|
862 | 855 | |
|
863 | 856 | def _repr_png_(self): |
|
864 | 857 | # TODO |
|
865 | 858 | pass |
|
866 | 859 | def _repr_jpeg_(self): |
|
867 | 860 | # TODO |
|
868 | 861 | pass |
|
869 | 862 | |
|
870 | 863 | def clear_output(wait=False): |
|
871 | 864 | """Clear the output of the current cell receiving output. |
|
872 | 865 | |
|
873 | 866 | Parameters |
|
874 | 867 | ---------- |
|
875 | 868 | wait : bool [default: false] |
|
876 | 869 | Wait to clear the output until new output is available to replace it.""" |
|
877 | 870 | from IPython.core.interactiveshell import InteractiveShell |
|
878 | 871 | if InteractiveShell.initialized(): |
|
879 | 872 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
880 | 873 | else: |
|
881 | 874 | from IPython.utils import io |
|
882 | 875 | print('\033[2K\r', file=io.stdout, end='') |
|
883 | 876 | io.stdout.flush() |
|
884 | 877 | print('\033[2K\r', file=io.stderr, end='') |
|
885 | 878 | io.stderr.flush() |
|
886 | 879 | |
|
887 | 880 | |
|
888 | 881 | @skip_doctest |
|
889 | 882 | def set_matplotlib_formats(*formats, **kwargs): |
|
890 | 883 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
|
891 | 884 | |
|
892 | 885 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: |
|
893 | 886 | |
|
894 | 887 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) |
|
895 | 888 | |
|
896 | 889 | To set this in your config files use the following:: |
|
897 | 890 | |
|
898 | 891 | c.InlineBackend.figure_formats = {'png', 'jpeg'} |
|
899 | 892 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) |
|
900 | 893 | |
|
901 | 894 | Parameters |
|
902 | 895 | ---------- |
|
903 | 896 | *formats : strs |
|
904 | 897 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
|
905 | 898 | **kwargs : |
|
906 | 899 | Keyword args will be relayed to ``figure.canvas.print_figure``. |
|
907 | 900 | """ |
|
908 | 901 | from IPython.core.interactiveshell import InteractiveShell |
|
909 | 902 | from IPython.core.pylabtools import select_figure_formats |
|
910 | 903 | from IPython.kernel.zmq.pylab.config import InlineBackend |
|
911 | 904 | # build kwargs, starting with InlineBackend config |
|
912 | 905 | kw = {} |
|
913 | 906 | cfg = InlineBackend.instance() |
|
914 | 907 | kw.update(cfg.print_figure_kwargs) |
|
915 | 908 | kw.update(**kwargs) |
|
916 | 909 | shell = InteractiveShell.instance() |
|
917 | 910 | select_figure_formats(shell, formats, **kw) |
|
918 | 911 | |
|
919 | 912 | @skip_doctest |
|
920 | 913 | def set_matplotlib_close(close=True): |
|
921 | 914 | """Set whether the inline backend closes all figures automatically or not. |
|
922 | 915 | |
|
923 | 916 | By default, the inline backend used in the IPython Notebook will close all |
|
924 | 917 | matplotlib figures automatically after each cell is run. This means that |
|
925 | 918 | plots in different cells won't interfere. Sometimes, you may want to make |
|
926 | 919 | a plot in one cell and then refine it in later cells. This can be accomplished |
|
927 | 920 | by:: |
|
928 | 921 | |
|
929 | 922 | In [1]: set_matplotlib_close(False) |
|
930 | 923 | |
|
931 | 924 | To set this in your config files use the following:: |
|
932 | 925 | |
|
933 | 926 | c.InlineBackend.close_figures = False |
|
934 | 927 | |
|
935 | 928 | Parameters |
|
936 | 929 | ---------- |
|
937 | 930 | close : bool |
|
938 | 931 | Should all matplotlib figures be automatically closed after each cell is |
|
939 | 932 | run? |
|
940 | 933 | """ |
|
941 | 934 | from IPython.kernel.zmq.pylab.config import InlineBackend |
|
942 | 935 | cfg = InlineBackend.instance() |
|
943 | 936 | cfg.close_figures = close |
|
944 | 937 |
@@ -1,282 +1,275 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 | from __future__ import print_function |
|
11 | 11 | |
|
12 | 12 | import sys |
|
13 | 13 | |
|
14 | 14 | from IPython.core.formatters import _safe_get_formatter_method |
|
15 | 15 | from IPython.config.configurable import Configurable |
|
16 | 16 | from IPython.utils import io |
|
17 | 17 | from IPython.utils.py3compat import builtin_mod |
|
18 | 18 | from IPython.utils.traitlets import Instance, Float |
|
19 | 19 | from IPython.utils.warn import warn |
|
20 | 20 | |
|
21 | 21 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
22 | 22 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
23 | 23 | # only and the other objects should ask that one object for their values. |
|
24 | 24 | |
|
25 | 25 | class DisplayHook(Configurable): |
|
26 | 26 | """The custom IPython displayhook to replace sys.displayhook. |
|
27 | 27 | |
|
28 | 28 | This class does many things, but the basic idea is that it is a callable |
|
29 | 29 | that gets called anytime user code returns a value. |
|
30 | 30 | """ |
|
31 | 31 | |
|
32 | 32 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
33 | 33 | cull_fraction = Float(0.2) |
|
34 | 34 | |
|
35 | 35 | def __init__(self, shell=None, cache_size=1000, **kwargs): |
|
36 | 36 | super(DisplayHook, self).__init__(shell=shell, **kwargs) |
|
37 | 37 | cache_size_min = 3 |
|
38 | 38 | if cache_size <= 0: |
|
39 | 39 | self.do_full_cache = 0 |
|
40 | 40 | cache_size = 0 |
|
41 | 41 | elif cache_size < cache_size_min: |
|
42 | 42 | self.do_full_cache = 0 |
|
43 | 43 | cache_size = 0 |
|
44 | 44 | warn('caching was disabled (min value for cache size is %s).' % |
|
45 | 45 | cache_size_min,level=3) |
|
46 | 46 | else: |
|
47 | 47 | self.do_full_cache = 1 |
|
48 | 48 | |
|
49 | 49 | self.cache_size = cache_size |
|
50 | 50 | |
|
51 | 51 | # we need a reference to the user-level namespace |
|
52 | 52 | self.shell = shell |
|
53 | 53 | |
|
54 | 54 | self._,self.__,self.___ = '','','' |
|
55 | 55 | |
|
56 | 56 | # these are deliberately global: |
|
57 | 57 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
58 | 58 | self.shell.user_ns.update(to_user_ns) |
|
59 | 59 | |
|
60 | 60 | @property |
|
61 | 61 | def prompt_count(self): |
|
62 | 62 | return self.shell.execution_count |
|
63 | 63 | |
|
64 | 64 | #------------------------------------------------------------------------- |
|
65 | 65 | # Methods used in __call__. Override these methods to modify the behavior |
|
66 | 66 | # of the displayhook. |
|
67 | 67 | #------------------------------------------------------------------------- |
|
68 | 68 | |
|
69 | 69 | def check_for_underscore(self): |
|
70 | 70 | """Check if the user has set the '_' variable by hand.""" |
|
71 | 71 | # If something injected a '_' variable in __builtin__, delete |
|
72 | 72 | # ipython's automatic one so we don't clobber that. gettext() in |
|
73 | 73 | # particular uses _, so we need to stay away from it. |
|
74 | 74 | if '_' in builtin_mod.__dict__: |
|
75 | 75 | try: |
|
76 | 76 | del self.shell.user_ns['_'] |
|
77 | 77 | except KeyError: |
|
78 | 78 | pass |
|
79 | 79 | |
|
80 | 80 | def quiet(self): |
|
81 | 81 | """Should we silence the display hook because of ';'?""" |
|
82 | 82 | # do not print output if input ends in ';' |
|
83 | 83 | try: |
|
84 | 84 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] |
|
85 | 85 | return cell.rstrip().endswith(';') |
|
86 | 86 | except IndexError: |
|
87 | 87 | # some uses of ipshellembed may fail here |
|
88 | 88 | return False |
|
89 | 89 | |
|
90 | 90 | def start_displayhook(self): |
|
91 | 91 | """Start the displayhook, initializing resources.""" |
|
92 | 92 | pass |
|
93 | 93 | |
|
94 | 94 | def write_output_prompt(self): |
|
95 | 95 | """Write the output prompt. |
|
96 | 96 | |
|
97 | 97 | The default implementation simply writes the prompt to |
|
98 | 98 | ``io.stdout``. |
|
99 | 99 | """ |
|
100 | 100 | # Use write, not print which adds an extra space. |
|
101 | 101 | io.stdout.write(self.shell.separate_out) |
|
102 | 102 | outprompt = self.shell.prompt_manager.render('out') |
|
103 | 103 | if self.do_full_cache: |
|
104 | 104 | io.stdout.write(outprompt) |
|
105 | 105 | |
|
106 | 106 | def compute_format_data(self, result): |
|
107 | 107 | """Compute format data of the object to be displayed. |
|
108 | 108 | |
|
109 | 109 | The format data is a generalization of the :func:`repr` of an object. |
|
110 | 110 | In the default implementation the format data is a :class:`dict` of |
|
111 | 111 | key value pair where the keys are valid MIME types and the values |
|
112 | 112 | are JSON'able data structure containing the raw data for that MIME |
|
113 | 113 | type. It is up to frontends to determine pick a MIME to to use and |
|
114 | 114 | display that data in an appropriate manner. |
|
115 | 115 | |
|
116 | 116 | This method only computes the format data for the object and should |
|
117 | 117 | NOT actually print or write that to a stream. |
|
118 | 118 | |
|
119 | 119 | Parameters |
|
120 | 120 | ---------- |
|
121 | 121 | result : object |
|
122 | 122 | The Python object passed to the display hook, whose format will be |
|
123 | 123 | computed. |
|
124 | 124 | |
|
125 | 125 | Returns |
|
126 | 126 | ------- |
|
127 | 127 | (format_dict, md_dict) : dict |
|
128 | 128 | format_dict is a :class:`dict` whose keys are valid MIME types and values are |
|
129 | 129 | JSON'able raw data for that MIME type. It is recommended that |
|
130 | 130 | all return values of this should always include the "text/plain" |
|
131 | 131 | MIME type representation of the object. |
|
132 | 132 | md_dict is a :class:`dict` with the same MIME type keys |
|
133 | 133 | of metadata associated with each output. |
|
134 | 134 | |
|
135 | 135 | """ |
|
136 | 136 | return self.shell.display_formatter.format(result) |
|
137 | 137 | |
|
138 | 138 | def write_format_data(self, format_dict, md_dict=None): |
|
139 | 139 | """Write the format data dict to the frontend. |
|
140 | 140 | |
|
141 | 141 | This default version of this method simply writes the plain text |
|
142 | 142 | representation of the object to ``io.stdout``. Subclasses should |
|
143 | 143 | override this method to send the entire `format_dict` to the |
|
144 | 144 | frontends. |
|
145 | 145 | |
|
146 | 146 | Parameters |
|
147 | 147 | ---------- |
|
148 | 148 | format_dict : dict |
|
149 | 149 | The format dict for the object passed to `sys.displayhook`. |
|
150 | 150 | md_dict : dict (optional) |
|
151 | 151 | The metadata dict to be associated with the display data. |
|
152 | 152 | """ |
|
153 | 153 | if 'text/plain' not in format_dict: |
|
154 | 154 | # nothing to do |
|
155 | 155 | return |
|
156 | 156 | # We want to print because we want to always make sure we have a |
|
157 | 157 | # newline, even if all the prompt separators are ''. This is the |
|
158 | 158 | # standard IPython behavior. |
|
159 | 159 | result_repr = format_dict['text/plain'] |
|
160 | 160 | if '\n' in result_repr: |
|
161 | 161 | # So that multi-line strings line up with the left column of |
|
162 | 162 | # the screen, instead of having the output prompt mess up |
|
163 | 163 | # their first line. |
|
164 | 164 | # We use the prompt template instead of the expanded prompt |
|
165 | 165 | # because the expansion may add ANSI escapes that will interfere |
|
166 | 166 | # with our ability to determine whether or not we should add |
|
167 | 167 | # a newline. |
|
168 | 168 | prompt_template = self.shell.prompt_manager.out_template |
|
169 | 169 | if prompt_template and not prompt_template.endswith('\n'): |
|
170 | 170 | # But avoid extraneous empty lines. |
|
171 | 171 | result_repr = '\n' + result_repr |
|
172 | 172 | |
|
173 | 173 | print(result_repr, file=io.stdout) |
|
174 | 174 | |
|
175 | 175 | def update_user_ns(self, result): |
|
176 | 176 | """Update user_ns with various things like _, __, _1, etc.""" |
|
177 | 177 | |
|
178 | 178 | # Avoid recursive reference when displaying _oh/Out |
|
179 | 179 | if result is not self.shell.user_ns['_oh']: |
|
180 | 180 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
181 | 181 | self.cull_cache() |
|
182 | 182 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
183 | 183 | # we cause buggy behavior for things like gettext). |
|
184 | 184 | |
|
185 | 185 | if '_' not in builtin_mod.__dict__: |
|
186 | 186 | self.___ = self.__ |
|
187 | 187 | self.__ = self._ |
|
188 | 188 | self._ = result |
|
189 | 189 | self.shell.push({'_':self._, |
|
190 | 190 | '__':self.__, |
|
191 | 191 | '___':self.___}, interactive=False) |
|
192 | 192 | |
|
193 | 193 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
194 | 194 | to_main = {} |
|
195 | 195 | if self.do_full_cache: |
|
196 | 196 | new_result = '_'+repr(self.prompt_count) |
|
197 | 197 | to_main[new_result] = result |
|
198 | 198 | self.shell.push(to_main, interactive=False) |
|
199 | 199 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
200 | 200 | |
|
201 | 201 | def log_output(self, format_dict): |
|
202 | 202 | """Log the output.""" |
|
203 | 203 | if 'text/plain' not in format_dict: |
|
204 | 204 | # nothing to do |
|
205 | 205 | return |
|
206 | 206 | if self.shell.logger.log_output: |
|
207 | 207 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
208 | 208 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
209 | 209 | format_dict['text/plain'] |
|
210 | 210 | |
|
211 | 211 | def finish_displayhook(self): |
|
212 | 212 | """Finish up all displayhook activities.""" |
|
213 | 213 | io.stdout.write(self.shell.separate_out2) |
|
214 | 214 | io.stdout.flush() |
|
215 | 215 | |
|
216 | 216 | def __call__(self, result=None): |
|
217 | 217 | """Printing with history cache management. |
|
218 | 218 | |
|
219 | 219 | This is invoked everytime the interpreter needs to print, and is |
|
220 | 220 | activated by setting the variable sys.displayhook to it. |
|
221 | 221 | """ |
|
222 | 222 | self.check_for_underscore() |
|
223 | 223 | if result is not None and not self.quiet(): |
|
224 | # If _ipython_display_ is defined, use that to display this object. | |
|
225 | display_method = _safe_get_formatter_method(result, '_ipython_display_') | |
|
226 | if display_method is not None: | |
|
227 | try: | |
|
228 | return display_method() | |
|
229 | except NotImplementedError: | |
|
230 | pass | |
|
231 | ||
|
232 | 224 | self.start_displayhook() |
|
233 | 225 | self.write_output_prompt() |
|
234 | 226 | format_dict, md_dict = self.compute_format_data(result) |
|
235 | self.write_format_data(format_dict, md_dict) | |
|
236 | 227 | self.update_user_ns(result) |
|
237 |
|
|
|
228 | if format_dict: | |
|
229 | self.write_format_data(format_dict, md_dict) | |
|
230 | self.log_output(format_dict) | |
|
238 | 231 | self.finish_displayhook() |
|
239 | 232 | |
|
240 | 233 | def cull_cache(self): |
|
241 | 234 | """Output cache is full, cull the oldest entries""" |
|
242 | 235 | oh = self.shell.user_ns.get('_oh', {}) |
|
243 | 236 | sz = len(oh) |
|
244 | 237 | cull_count = max(int(sz * self.cull_fraction), 2) |
|
245 | 238 | warn('Output cache limit (currently {sz} entries) hit.\n' |
|
246 | 239 | 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count)) |
|
247 | 240 | |
|
248 | 241 | for i, n in enumerate(sorted(oh)): |
|
249 | 242 | if i >= cull_count: |
|
250 | 243 | break |
|
251 | 244 | self.shell.user_ns.pop('_%i' % n, None) |
|
252 | 245 | oh.pop(n, None) |
|
253 | 246 | |
|
254 | 247 | |
|
255 | 248 | def flush(self): |
|
256 | 249 | if not self.do_full_cache: |
|
257 | 250 | raise ValueError("You shouldn't have reached the cache flush " |
|
258 | 251 | "if full caching is not enabled!") |
|
259 | 252 | # delete auto-generated vars from global namespace |
|
260 | 253 | |
|
261 | 254 | for n in range(1,self.prompt_count + 1): |
|
262 | 255 | key = '_'+repr(n) |
|
263 | 256 | try: |
|
264 | 257 | del self.shell.user_ns[key] |
|
265 | 258 | except: pass |
|
266 | 259 | # In some embedded circumstances, the user_ns doesn't have the |
|
267 | 260 | # '_oh' key set up. |
|
268 | 261 | oh = self.shell.user_ns.get('_oh', None) |
|
269 | 262 | if oh is not None: |
|
270 | 263 | oh.clear() |
|
271 | 264 | |
|
272 | 265 | # Release our own references to objects: |
|
273 | 266 | self._, self.__, self.___ = '', '', '' |
|
274 | 267 | |
|
275 | 268 | if '_' not in builtin_mod.__dict__: |
|
276 | 269 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
277 | 270 | import gc |
|
278 | 271 | # TODO: Is this really needed? |
|
279 | 272 | # IronPython blocks here forever |
|
280 | 273 | if sys.platform != "cli": |
|
281 | 274 | gc.collect() |
|
282 | 275 |
@@ -1,895 +1,939 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Display formatters. |
|
3 | 3 | |
|
4 | 4 | Inheritance diagram: |
|
5 | 5 | |
|
6 | 6 | .. inheritance-diagram:: IPython.core.formatters |
|
7 | 7 | :parts: 3 |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | # Copyright (c) IPython Development Team. |
|
11 | 11 | # Distributed under the terms of the Modified BSD License. |
|
12 | 12 | |
|
13 | 13 | import abc |
|
14 | 14 | import inspect |
|
15 | 15 | import sys |
|
16 | 16 | import traceback |
|
17 | 17 | import types |
|
18 | 18 | import warnings |
|
19 | 19 | |
|
20 | 20 | from IPython.external.decorator import decorator |
|
21 | 21 | |
|
22 | 22 | from IPython.config.configurable import Configurable |
|
23 | 23 | from IPython.core.getipython import get_ipython |
|
24 | 24 | from IPython.lib import pretty |
|
25 | 25 | from IPython.utils.traitlets import ( |
|
26 | 26 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
27 | Instance, | |
|
27 | 28 | ) |
|
28 | 29 | from IPython.utils.py3compat import ( |
|
29 | 30 | unicode_to_str, with_metaclass, PY3, string_types, unicode_type, |
|
30 | 31 | ) |
|
31 | 32 | |
|
32 | 33 | if PY3: |
|
33 | 34 | from io import StringIO |
|
34 | 35 | else: |
|
35 | 36 | from StringIO import StringIO |
|
36 | 37 | |
|
37 | 38 | |
|
38 | 39 | #----------------------------------------------------------------------------- |
|
39 | 40 | # The main DisplayFormatter class |
|
40 | 41 | #----------------------------------------------------------------------------- |
|
41 | 42 | |
|
42 | 43 | |
|
43 | 44 | def _safe_get_formatter_method(obj, name): |
|
44 | 45 | """Safely get a formatter method |
|
45 | 46 | |
|
46 | 47 | - Classes cannot have formatter methods, only instance |
|
47 | 48 | - protect against proxy objects that claim to have everything |
|
48 | 49 | """ |
|
49 | 50 | if inspect.isclass(obj): |
|
50 | 51 | # repr methods only make sense on instances, not classes |
|
51 | 52 | return None |
|
52 | 53 | method = pretty._safe_getattr(obj, name, None) |
|
53 | 54 | if callable(method): |
|
54 | 55 | # obj claims to have repr method... |
|
55 | 56 | if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)): |
|
56 | 57 | # ...but don't trust proxy objects that claim to have everything |
|
57 | 58 | return None |
|
58 | 59 | return method |
|
59 | 60 | |
|
60 | 61 | |
|
61 | 62 | class DisplayFormatter(Configurable): |
|
62 | 63 | |
|
63 | 64 | # When set to true only the default plain text formatter will be used. |
|
64 | 65 | plain_text_only = Bool(False, config=True) |
|
65 | 66 | def _plain_text_only_changed(self, name, old, new): |
|
66 | 67 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
67 | 68 | |
|
68 | 69 | Use DisplayFormatter.active_types = ['text/plain'] |
|
69 | 70 | for the same effect. |
|
70 | 71 | """, DeprecationWarning) |
|
71 | 72 | if new: |
|
72 | 73 | self.active_types = ['text/plain'] |
|
73 | 74 | else: |
|
74 | 75 | self.active_types = self.format_types |
|
75 | 76 | |
|
76 | 77 | active_types = List(Unicode, config=True, |
|
77 | 78 | help="""List of currently active mime-types to display. |
|
78 | 79 | You can use this to set a white-list for formats to display. |
|
79 | 80 | |
|
80 | 81 | Most users will not need to change this value. |
|
81 | 82 | """) |
|
82 | 83 | def _active_types_default(self): |
|
83 | 84 | return self.format_types |
|
84 | 85 | |
|
85 | 86 | def _active_types_changed(self, name, old, new): |
|
86 | 87 | for key, formatter in self.formatters.items(): |
|
87 | 88 | if key in new: |
|
88 | 89 | formatter.enabled = True |
|
89 | 90 | else: |
|
90 | 91 | formatter.enabled = False |
|
91 | 92 | |
|
93 | self_formatter = Instance(__name__ +'.SelfDisplayingFormatter') | |
|
94 | def _self_formatter_default(self): | |
|
95 | return SelfDisplayingFormatter(parent=self) | |
|
96 | ||
|
92 | 97 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
93 | 98 | # values are subclasses of BaseFormatter. |
|
94 | 99 | formatters = Dict() |
|
95 | 100 | def _formatters_default(self): |
|
96 | 101 | """Activate the default formatters.""" |
|
97 | 102 | formatter_classes = [ |
|
98 | 103 | PlainTextFormatter, |
|
99 | 104 | HTMLFormatter, |
|
100 | 105 | MarkdownFormatter, |
|
101 | 106 | SVGFormatter, |
|
102 | 107 | PNGFormatter, |
|
103 | 108 | PDFFormatter, |
|
104 | 109 | JPEGFormatter, |
|
105 | 110 | LatexFormatter, |
|
106 | 111 | JSONFormatter, |
|
107 | 112 | JavascriptFormatter |
|
108 | 113 | ] |
|
109 | 114 | d = {} |
|
110 | 115 | for cls in formatter_classes: |
|
111 | 116 | f = cls(parent=self) |
|
112 | 117 | d[f.format_type] = f |
|
113 | 118 | return d |
|
114 | 119 | |
|
115 | 120 | def format(self, obj, include=None, exclude=None): |
|
116 | 121 | """Return a format data dict for an object. |
|
117 | 122 | |
|
118 | 123 | By default all format types will be computed. |
|
119 | 124 | |
|
120 | 125 | The following MIME types are currently implemented: |
|
121 | 126 | |
|
122 | 127 | * text/plain |
|
123 | 128 | * text/html |
|
124 | 129 | * text/markdown |
|
125 | 130 | * text/latex |
|
126 | 131 | * application/json |
|
127 | 132 | * application/javascript |
|
128 | 133 | * application/pdf |
|
129 | 134 | * image/png |
|
130 | 135 | * image/jpeg |
|
131 | 136 | * image/svg+xml |
|
132 | 137 | |
|
133 | 138 | Parameters |
|
134 | 139 | ---------- |
|
135 | 140 | obj : object |
|
136 | 141 | The Python object whose format data will be computed. |
|
137 | 142 | include : list or tuple, optional |
|
138 | 143 | A list of format type strings (MIME types) to include in the |
|
139 | 144 | format data dict. If this is set *only* the format types included |
|
140 | 145 | in this list will be computed. |
|
141 | 146 | exclude : list or tuple, optional |
|
142 | 147 | A list of format type string (MIME types) to exclude in the format |
|
143 | 148 | data dict. If this is set all format types will be computed, |
|
144 | 149 | except for those included in this argument. |
|
145 | 150 | |
|
146 | 151 | Returns |
|
147 | 152 | ------- |
|
148 | 153 | (format_dict, metadata_dict) : tuple of two dicts |
|
149 | 154 | |
|
150 | 155 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
151 | 156 | generated for the object. The keys are the format types, which |
|
152 | 157 | will usually be MIME type strings and the values and JSON'able |
|
153 | 158 | data structure containing the raw data for the representation in |
|
154 | 159 | that format. |
|
155 | 160 | |
|
156 | 161 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
157 | 162 | Its keys will be a strict subset of the keys in format_dict. |
|
158 | 163 | """ |
|
159 | 164 | format_dict = {} |
|
160 | 165 | md_dict = {} |
|
161 | ||
|
166 | ||
|
167 | if self.self_formatter(obj): | |
|
168 | # object handled itself, don't proceed | |
|
169 | return {}, {} | |
|
170 | ||
|
162 | 171 | for format_type, formatter in self.formatters.items(): |
|
163 | 172 | if include and format_type not in include: |
|
164 | 173 | continue |
|
165 | 174 | if exclude and format_type in exclude: |
|
166 | 175 | continue |
|
167 | 176 | |
|
168 | 177 | md = None |
|
169 | 178 | try: |
|
170 | 179 | data = formatter(obj) |
|
171 | 180 | except: |
|
172 | 181 | # FIXME: log the exception |
|
173 | 182 | raise |
|
174 | 183 | |
|
175 | 184 | # formatters can return raw data or (data, metadata) |
|
176 | 185 | if isinstance(data, tuple) and len(data) == 2: |
|
177 | 186 | data, md = data |
|
178 | 187 | |
|
179 | 188 | if data is not None: |
|
180 | 189 | format_dict[format_type] = data |
|
181 | 190 | if md is not None: |
|
182 | 191 | md_dict[format_type] = md |
|
183 | 192 | |
|
184 | 193 | return format_dict, md_dict |
|
185 | 194 | |
|
186 | 195 | @property |
|
187 | 196 | def format_types(self): |
|
188 | 197 | """Return the format types (MIME types) of the active formatters.""" |
|
189 | 198 | return list(self.formatters.keys()) |
|
190 | 199 | |
|
191 | 200 | |
|
192 | 201 | #----------------------------------------------------------------------------- |
|
193 | 202 | # Formatters for specific format types (text, html, svg, etc.) |
|
194 | 203 | #----------------------------------------------------------------------------- |
|
195 | 204 | |
|
196 | 205 | |
|
197 | 206 | def _safe_repr(obj): |
|
198 | 207 | """Try to return a repr of an object |
|
199 | 208 | |
|
200 | 209 | always returns a string, at least. |
|
201 | 210 | """ |
|
202 | 211 | try: |
|
203 | 212 | return repr(obj) |
|
204 | 213 | except Exception as e: |
|
205 | 214 | return "un-repr-able object (%r)" % e |
|
206 | 215 | |
|
207 | 216 | |
|
208 | 217 | class FormatterWarning(UserWarning): |
|
209 | 218 | """Warning class for errors in formatters""" |
|
210 | 219 | |
|
211 | 220 | @decorator |
|
212 | 221 | def warn_format_error(method, self, *args, **kwargs): |
|
213 | 222 | """decorator for warning on failed format call""" |
|
214 | 223 | try: |
|
215 | 224 | r = method(self, *args, **kwargs) |
|
216 | 225 | except NotImplementedError: |
|
217 | 226 | # don't warn on NotImplementedErrors |
|
218 | 227 | return None |
|
219 | 228 | except Exception: |
|
220 | 229 | exc_info = sys.exc_info() |
|
221 | 230 | ip = get_ipython() |
|
222 | 231 | if ip is not None: |
|
223 | 232 | ip.showtraceback(exc_info) |
|
224 | 233 | else: |
|
225 | 234 | traceback.print_exception(*exc_info) |
|
226 | 235 | return None |
|
227 | 236 | if r is None or isinstance(r, self._return_type) or \ |
|
228 | 237 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): |
|
229 | 238 | return r |
|
230 | 239 | else: |
|
231 | 240 | warnings.warn( |
|
232 | 241 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ |
|
233 | 242 | (self.format_type, type(r), self._return_type, _safe_repr(args[0])), |
|
234 | 243 | FormatterWarning |
|
235 | 244 | ) |
|
236 | 245 | |
|
237 | 246 | |
|
238 | 247 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
239 | 248 | """ Abstract base class for Formatters. |
|
240 | 249 | |
|
241 | 250 | A formatter is a callable class that is responsible for computing the |
|
242 | 251 | raw format data for a particular format type (MIME type). For example, |
|
243 | 252 | an HTML formatter would have a format type of `text/html` and would return |
|
244 | 253 | the HTML representation of the object when called. |
|
245 | 254 | """ |
|
246 | 255 | |
|
247 | 256 | # The format type of the data returned, usually a MIME type. |
|
248 | 257 | format_type = 'text/plain' |
|
249 | 258 | |
|
250 | 259 | # Is the formatter enabled... |
|
251 | 260 | enabled = True |
|
252 | 261 | |
|
253 | 262 | @abc.abstractmethod |
|
254 | 263 | @warn_format_error |
|
255 | 264 | def __call__(self, obj): |
|
256 | 265 | """Return a JSON'able representation of the object. |
|
257 | 266 | |
|
258 | 267 | If the object cannot be formatted by this formatter, |
|
259 | 268 | warn and return None. |
|
260 | 269 | """ |
|
261 | 270 | return repr(obj) |
|
262 | 271 | |
|
263 | 272 | |
|
264 | 273 | def _mod_name_key(typ): |
|
265 | 274 | """Return a (__module__, __name__) tuple for a type. |
|
266 | 275 | |
|
267 | 276 | Used as key in Formatter.deferred_printers. |
|
268 | 277 | """ |
|
269 | 278 | module = getattr(typ, '__module__', None) |
|
270 | 279 | name = getattr(typ, '__name__', None) |
|
271 | 280 | return (module, name) |
|
272 | 281 | |
|
273 | 282 | |
|
274 | 283 | def _get_type(obj): |
|
275 | 284 | """Return the type of an instance (old and new-style)""" |
|
276 | 285 | return getattr(obj, '__class__', None) or type(obj) |
|
277 | 286 | |
|
278 | 287 | _raise_key_error = object() |
|
279 | 288 | |
|
280 | 289 | |
|
281 | 290 | class BaseFormatter(Configurable): |
|
282 | 291 | """A base formatter class that is configurable. |
|
283 | 292 | |
|
284 | 293 | This formatter should usually be used as the base class of all formatters. |
|
285 | 294 | It is a traited :class:`Configurable` class and includes an extensible |
|
286 | 295 | API for users to determine how their objects are formatted. The following |
|
287 | 296 | logic is used to find a function to format an given object. |
|
288 | 297 | |
|
289 | 298 | 1. The object is introspected to see if it has a method with the name |
|
290 | 299 | :attr:`print_method`. If is does, that object is passed to that method |
|
291 | 300 | for formatting. |
|
292 | 301 | 2. If no print method is found, three internal dictionaries are consulted |
|
293 | 302 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
294 | 303 | and :attr:`deferred_printers`. |
|
295 | 304 | |
|
296 | 305 | Users should use these dictionaries to register functions that will be |
|
297 | 306 | used to compute the format data for their objects (if those objects don't |
|
298 | 307 | have the special print methods). The easiest way of using these |
|
299 | 308 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
300 | 309 | methods. |
|
301 | 310 | |
|
302 | 311 | If no function/callable is found to compute the format data, ``None`` is |
|
303 | 312 | returned and this format type is not used. |
|
304 | 313 | """ |
|
305 | 314 | |
|
306 | 315 | format_type = Unicode('text/plain') |
|
307 | 316 | _return_type = string_types |
|
308 | 317 | |
|
309 | 318 | enabled = Bool(True, config=True) |
|
310 | 319 | |
|
311 | 320 | print_method = ObjectName('__repr__') |
|
312 | 321 | |
|
313 | 322 | # The singleton printers. |
|
314 | 323 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
315 | 324 | singleton_printers = Dict(config=True) |
|
316 | 325 | |
|
317 | 326 | # The type-specific printers. |
|
318 | 327 | # Map type objects to the format functions. |
|
319 | 328 | type_printers = Dict(config=True) |
|
320 | 329 | |
|
321 | 330 | # The deferred-import type-specific printers. |
|
322 | 331 | # Map (modulename, classname) pairs to the format functions. |
|
323 | 332 | deferred_printers = Dict(config=True) |
|
324 | 333 | |
|
325 | 334 | @warn_format_error |
|
326 | 335 | def __call__(self, obj): |
|
327 | 336 | """Compute the format for an object.""" |
|
328 | 337 | if self.enabled: |
|
329 | 338 | # lookup registered printer |
|
330 | 339 | try: |
|
331 | 340 | printer = self.lookup(obj) |
|
332 | 341 | except KeyError: |
|
333 | 342 | pass |
|
334 | 343 | else: |
|
335 | 344 | return printer(obj) |
|
336 | 345 | # Finally look for special method names |
|
337 | 346 | method = _safe_get_formatter_method(obj, self.print_method) |
|
338 | 347 | if method is not None: |
|
339 | 348 | return method() |
|
340 | 349 | return None |
|
341 | 350 | else: |
|
342 | 351 | return None |
|
343 | 352 | |
|
344 | 353 | def __contains__(self, typ): |
|
345 | 354 | """map in to lookup_by_type""" |
|
346 | 355 | try: |
|
347 | 356 | self.lookup_by_type(typ) |
|
348 | 357 | except KeyError: |
|
349 | 358 | return False |
|
350 | 359 | else: |
|
351 | 360 | return True |
|
352 | 361 | |
|
353 | 362 | def lookup(self, obj): |
|
354 | 363 | """Look up the formatter for a given instance. |
|
355 | 364 | |
|
356 | 365 | Parameters |
|
357 | 366 | ---------- |
|
358 | 367 | obj : object instance |
|
359 | 368 | |
|
360 | 369 | Returns |
|
361 | 370 | ------- |
|
362 | 371 | f : callable |
|
363 | 372 | The registered formatting callable for the type. |
|
364 | 373 | |
|
365 | 374 | Raises |
|
366 | 375 | ------ |
|
367 | 376 | KeyError if the type has not been registered. |
|
368 | 377 | """ |
|
369 | 378 | # look for singleton first |
|
370 | 379 | obj_id = id(obj) |
|
371 | 380 | if obj_id in self.singleton_printers: |
|
372 | 381 | return self.singleton_printers[obj_id] |
|
373 | 382 | # then lookup by type |
|
374 | 383 | return self.lookup_by_type(_get_type(obj)) |
|
375 | 384 | |
|
376 | 385 | def lookup_by_type(self, typ): |
|
377 | 386 | """Look up the registered formatter for a type. |
|
378 | 387 | |
|
379 | 388 | Parameters |
|
380 | 389 | ---------- |
|
381 | 390 | typ : type or '__module__.__name__' string for a type |
|
382 | 391 | |
|
383 | 392 | Returns |
|
384 | 393 | ------- |
|
385 | 394 | f : callable |
|
386 | 395 | The registered formatting callable for the type. |
|
387 | 396 | |
|
388 | 397 | Raises |
|
389 | 398 | ------ |
|
390 | 399 | KeyError if the type has not been registered. |
|
391 | 400 | """ |
|
392 | 401 | if isinstance(typ, string_types): |
|
393 | 402 | typ_key = tuple(typ.rsplit('.',1)) |
|
394 | 403 | if typ_key not in self.deferred_printers: |
|
395 | 404 | # We may have it cached in the type map. We will have to |
|
396 | 405 | # iterate over all of the types to check. |
|
397 | 406 | for cls in self.type_printers: |
|
398 | 407 | if _mod_name_key(cls) == typ_key: |
|
399 | 408 | return self.type_printers[cls] |
|
400 | 409 | else: |
|
401 | 410 | return self.deferred_printers[typ_key] |
|
402 | 411 | else: |
|
403 | 412 | for cls in pretty._get_mro(typ): |
|
404 | 413 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
405 | 414 | return self.type_printers[cls] |
|
406 | 415 | |
|
407 | 416 | # If we have reached here, the lookup failed. |
|
408 | 417 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
409 | 418 | |
|
410 | 419 | def for_type(self, typ, func=None): |
|
411 | 420 | """Add a format function for a given type. |
|
412 | 421 | |
|
413 | 422 | Parameters |
|
414 | 423 | ----------- |
|
415 | 424 | typ : type or '__module__.__name__' string for a type |
|
416 | 425 | The class of the object that will be formatted using `func`. |
|
417 | 426 | func : callable |
|
418 | 427 | A callable for computing the format data. |
|
419 | 428 | `func` will be called with the object to be formatted, |
|
420 | 429 | and will return the raw data in this formatter's format. |
|
421 | 430 | Subclasses may use a different call signature for the |
|
422 | 431 | `func` argument. |
|
423 | 432 | |
|
424 | 433 | If `func` is None or not specified, there will be no change, |
|
425 | 434 | only returning the current value. |
|
426 | 435 | |
|
427 | 436 | Returns |
|
428 | 437 | ------- |
|
429 | 438 | oldfunc : callable |
|
430 | 439 | The currently registered callable. |
|
431 | 440 | If you are registering a new formatter, |
|
432 | 441 | this will be the previous value (to enable restoring later). |
|
433 | 442 | """ |
|
434 | 443 | # if string given, interpret as 'pkg.module.class_name' |
|
435 | 444 | if isinstance(typ, string_types): |
|
436 | 445 | type_module, type_name = typ.rsplit('.', 1) |
|
437 | 446 | return self.for_type_by_name(type_module, type_name, func) |
|
438 | 447 | |
|
439 | 448 | try: |
|
440 | 449 | oldfunc = self.lookup_by_type(typ) |
|
441 | 450 | except KeyError: |
|
442 | 451 | oldfunc = None |
|
443 | 452 | |
|
444 | 453 | if func is not None: |
|
445 | 454 | self.type_printers[typ] = func |
|
446 | 455 | |
|
447 | 456 | return oldfunc |
|
448 | 457 | |
|
449 | 458 | def for_type_by_name(self, type_module, type_name, func=None): |
|
450 | 459 | """Add a format function for a type specified by the full dotted |
|
451 | 460 | module and name of the type, rather than the type of the object. |
|
452 | 461 | |
|
453 | 462 | Parameters |
|
454 | 463 | ---------- |
|
455 | 464 | type_module : str |
|
456 | 465 | The full dotted name of the module the type is defined in, like |
|
457 | 466 | ``numpy``. |
|
458 | 467 | type_name : str |
|
459 | 468 | The name of the type (the class name), like ``dtype`` |
|
460 | 469 | func : callable |
|
461 | 470 | A callable for computing the format data. |
|
462 | 471 | `func` will be called with the object to be formatted, |
|
463 | 472 | and will return the raw data in this formatter's format. |
|
464 | 473 | Subclasses may use a different call signature for the |
|
465 | 474 | `func` argument. |
|
466 | 475 | |
|
467 | 476 | If `func` is None or unspecified, there will be no change, |
|
468 | 477 | only returning the current value. |
|
469 | 478 | |
|
470 | 479 | Returns |
|
471 | 480 | ------- |
|
472 | 481 | oldfunc : callable |
|
473 | 482 | The currently registered callable. |
|
474 | 483 | If you are registering a new formatter, |
|
475 | 484 | this will be the previous value (to enable restoring later). |
|
476 | 485 | """ |
|
477 | 486 | key = (type_module, type_name) |
|
478 | 487 | |
|
479 | 488 | try: |
|
480 | 489 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
481 | 490 | except KeyError: |
|
482 | 491 | oldfunc = None |
|
483 | 492 | |
|
484 | 493 | if func is not None: |
|
485 | 494 | self.deferred_printers[key] = func |
|
486 | 495 | return oldfunc |
|
487 | 496 | |
|
488 | 497 | def pop(self, typ, default=_raise_key_error): |
|
489 | 498 | """Pop a formatter for the given type. |
|
490 | 499 | |
|
491 | 500 | Parameters |
|
492 | 501 | ---------- |
|
493 | 502 | typ : type or '__module__.__name__' string for a type |
|
494 | 503 | default : object |
|
495 | 504 | value to be returned if no formatter is registered for typ. |
|
496 | 505 | |
|
497 | 506 | Returns |
|
498 | 507 | ------- |
|
499 | 508 | obj : object |
|
500 | 509 | The last registered object for the type. |
|
501 | 510 | |
|
502 | 511 | Raises |
|
503 | 512 | ------ |
|
504 | 513 | KeyError if the type is not registered and default is not specified. |
|
505 | 514 | """ |
|
506 | 515 | |
|
507 | 516 | if isinstance(typ, string_types): |
|
508 | 517 | typ_key = tuple(typ.rsplit('.',1)) |
|
509 | 518 | if typ_key not in self.deferred_printers: |
|
510 | 519 | # We may have it cached in the type map. We will have to |
|
511 | 520 | # iterate over all of the types to check. |
|
512 | 521 | for cls in self.type_printers: |
|
513 | 522 | if _mod_name_key(cls) == typ_key: |
|
514 | 523 | old = self.type_printers.pop(cls) |
|
515 | 524 | break |
|
516 | 525 | else: |
|
517 | 526 | old = default |
|
518 | 527 | else: |
|
519 | 528 | old = self.deferred_printers.pop(typ_key) |
|
520 | 529 | else: |
|
521 | 530 | if typ in self.type_printers: |
|
522 | 531 | old = self.type_printers.pop(typ) |
|
523 | 532 | else: |
|
524 | 533 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
525 | 534 | if old is _raise_key_error: |
|
526 | 535 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
527 | 536 | return old |
|
528 | 537 | |
|
529 | 538 | def _in_deferred_types(self, cls): |
|
530 | 539 | """ |
|
531 | 540 | Check if the given class is specified in the deferred type registry. |
|
532 | 541 | |
|
533 | 542 | Successful matches will be moved to the regular type registry for future use. |
|
534 | 543 | """ |
|
535 | 544 | mod = getattr(cls, '__module__', None) |
|
536 | 545 | name = getattr(cls, '__name__', None) |
|
537 | 546 | key = (mod, name) |
|
538 | 547 | if key in self.deferred_printers: |
|
539 | 548 | # Move the printer over to the regular registry. |
|
540 | 549 | printer = self.deferred_printers.pop(key) |
|
541 | 550 | self.type_printers[cls] = printer |
|
542 | 551 | return True |
|
543 | 552 | return False |
|
544 | 553 | |
|
545 | 554 | |
|
546 | 555 | class PlainTextFormatter(BaseFormatter): |
|
547 | 556 | """The default pretty-printer. |
|
548 | 557 | |
|
549 | 558 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
550 | 559 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
551 | 560 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
552 | 561 | how to write pretty printers. Here is a simple example:: |
|
553 | 562 | |
|
554 | 563 | def dtype_pprinter(obj, p, cycle): |
|
555 | 564 | if cycle: |
|
556 | 565 | return p.text('dtype(...)') |
|
557 | 566 | if hasattr(obj, 'fields'): |
|
558 | 567 | if obj.fields is None: |
|
559 | 568 | p.text(repr(obj)) |
|
560 | 569 | else: |
|
561 | 570 | p.begin_group(7, 'dtype([') |
|
562 | 571 | for i, field in enumerate(obj.descr): |
|
563 | 572 | if i > 0: |
|
564 | 573 | p.text(',') |
|
565 | 574 | p.breakable() |
|
566 | 575 | p.pretty(field) |
|
567 | 576 | p.end_group(7, '])') |
|
568 | 577 | """ |
|
569 | 578 | |
|
570 | 579 | # The format type of data returned. |
|
571 | 580 | format_type = Unicode('text/plain') |
|
572 | 581 | |
|
573 | 582 | # This subclass ignores this attribute as it always need to return |
|
574 | 583 | # something. |
|
575 | 584 | enabled = Bool(True, config=False) |
|
576 | 585 | |
|
577 | 586 | max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True, |
|
578 | 587 | help="""Truncate large collections (lists, dicts, tuples, sets) to this size. |
|
579 | 588 | |
|
580 | 589 | Set to 0 to disable truncation. |
|
581 | 590 | """ |
|
582 | 591 | ) |
|
583 | 592 | |
|
584 | 593 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
585 | 594 | print_method = ObjectName('_repr_pretty_') |
|
586 | 595 | |
|
587 | 596 | # Whether to pretty-print or not. |
|
588 | 597 | pprint = Bool(True, config=True) |
|
589 | 598 | |
|
590 | 599 | # Whether to be verbose or not. |
|
591 | 600 | verbose = Bool(False, config=True) |
|
592 | 601 | |
|
593 | 602 | # The maximum width. |
|
594 | 603 | max_width = Integer(79, config=True) |
|
595 | 604 | |
|
596 | 605 | # The newline character. |
|
597 | 606 | newline = Unicode('\n', config=True) |
|
598 | 607 | |
|
599 | 608 | # format-string for pprinting floats |
|
600 | 609 | float_format = Unicode('%r') |
|
601 | 610 | # setter for float precision, either int or direct format-string |
|
602 | 611 | float_precision = CUnicode('', config=True) |
|
603 | 612 | |
|
604 | 613 | def _float_precision_changed(self, name, old, new): |
|
605 | 614 | """float_precision changed, set float_format accordingly. |
|
606 | 615 | |
|
607 | 616 | float_precision can be set by int or str. |
|
608 | 617 | This will set float_format, after interpreting input. |
|
609 | 618 | If numpy has been imported, numpy print precision will also be set. |
|
610 | 619 | |
|
611 | 620 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
612 | 621 | |
|
613 | 622 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
614 | 623 | |
|
615 | 624 | This parameter can be set via the '%precision' magic. |
|
616 | 625 | """ |
|
617 | 626 | |
|
618 | 627 | if '%' in new: |
|
619 | 628 | # got explicit format string |
|
620 | 629 | fmt = new |
|
621 | 630 | try: |
|
622 | 631 | fmt%3.14159 |
|
623 | 632 | except Exception: |
|
624 | 633 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
625 | 634 | elif new: |
|
626 | 635 | # otherwise, should be an int |
|
627 | 636 | try: |
|
628 | 637 | i = int(new) |
|
629 | 638 | assert i >= 0 |
|
630 | 639 | except ValueError: |
|
631 | 640 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
632 | 641 | except AssertionError: |
|
633 | 642 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
634 | 643 | |
|
635 | 644 | fmt = '%%.%if'%i |
|
636 | 645 | if 'numpy' in sys.modules: |
|
637 | 646 | # set numpy precision if it has been imported |
|
638 | 647 | import numpy |
|
639 | 648 | numpy.set_printoptions(precision=i) |
|
640 | 649 | else: |
|
641 | 650 | # default back to repr |
|
642 | 651 | fmt = '%r' |
|
643 | 652 | if 'numpy' in sys.modules: |
|
644 | 653 | import numpy |
|
645 | 654 | # numpy default is 8 |
|
646 | 655 | numpy.set_printoptions(precision=8) |
|
647 | 656 | self.float_format = fmt |
|
648 | 657 | |
|
649 | 658 | # Use the default pretty printers from IPython.lib.pretty. |
|
650 | 659 | def _singleton_printers_default(self): |
|
651 | 660 | return pretty._singleton_pprinters.copy() |
|
652 | 661 | |
|
653 | 662 | def _type_printers_default(self): |
|
654 | 663 | d = pretty._type_pprinters.copy() |
|
655 | 664 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
656 | 665 | return d |
|
657 | 666 | |
|
658 | 667 | def _deferred_printers_default(self): |
|
659 | 668 | return pretty._deferred_type_pprinters.copy() |
|
660 | 669 | |
|
661 | 670 | #### FormatterABC interface #### |
|
662 | 671 | |
|
663 | 672 | @warn_format_error |
|
664 | 673 | def __call__(self, obj): |
|
665 | 674 | """Compute the pretty representation of the object.""" |
|
666 | 675 | if not self.pprint: |
|
667 | 676 | return repr(obj) |
|
668 | 677 | else: |
|
669 | 678 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
670 | 679 | stream = StringIO() |
|
671 | 680 | # self.newline.encode() is a quick fix for issue gh-597. We need to |
|
672 | 681 | # ensure that stream does not get a mix of unicode and bytestrings, |
|
673 | 682 | # or it will cause trouble. |
|
674 | 683 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
675 | 684 | self.max_width, unicode_to_str(self.newline), |
|
676 | 685 | max_seq_length=self.max_seq_length, |
|
677 | 686 | singleton_pprinters=self.singleton_printers, |
|
678 | 687 | type_pprinters=self.type_printers, |
|
679 | 688 | deferred_pprinters=self.deferred_printers) |
|
680 | 689 | printer.pretty(obj) |
|
681 | 690 | printer.flush() |
|
682 | 691 | return stream.getvalue() |
|
683 | 692 | |
|
684 | 693 | |
|
685 | 694 | class HTMLFormatter(BaseFormatter): |
|
686 | 695 | """An HTML formatter. |
|
687 | 696 | |
|
688 | 697 | To define the callables that compute the HTML representation of your |
|
689 | 698 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
690 | 699 | or :meth:`for_type_by_name` methods to register functions that handle |
|
691 | 700 | this. |
|
692 | 701 | |
|
693 | 702 | The return value of this formatter should be a valid HTML snippet that |
|
694 | 703 | could be injected into an existing DOM. It should *not* include the |
|
695 | 704 | ```<html>`` or ```<body>`` tags. |
|
696 | 705 | """ |
|
697 | 706 | format_type = Unicode('text/html') |
|
698 | 707 | |
|
699 | 708 | print_method = ObjectName('_repr_html_') |
|
700 | 709 | |
|
701 | 710 | |
|
702 | 711 | class MarkdownFormatter(BaseFormatter): |
|
703 | 712 | """A Markdown formatter. |
|
704 | 713 | |
|
705 | 714 | To define the callables that compute the Markdown representation of your |
|
706 | 715 | objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` |
|
707 | 716 | or :meth:`for_type_by_name` methods to register functions that handle |
|
708 | 717 | this. |
|
709 | 718 | |
|
710 | 719 | The return value of this formatter should be a valid Markdown. |
|
711 | 720 | """ |
|
712 | 721 | format_type = Unicode('text/markdown') |
|
713 | 722 | |
|
714 | 723 | print_method = ObjectName('_repr_markdown_') |
|
715 | 724 | |
|
716 | 725 | class SVGFormatter(BaseFormatter): |
|
717 | 726 | """An SVG formatter. |
|
718 | 727 | |
|
719 | 728 | To define the callables that compute the SVG representation of your |
|
720 | 729 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
721 | 730 | or :meth:`for_type_by_name` methods to register functions that handle |
|
722 | 731 | this. |
|
723 | 732 | |
|
724 | 733 | The return value of this formatter should be valid SVG enclosed in |
|
725 | 734 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
726 | 735 | *not* include the ```<html>`` or ```<body>`` tags. |
|
727 | 736 | """ |
|
728 | 737 | format_type = Unicode('image/svg+xml') |
|
729 | 738 | |
|
730 | 739 | print_method = ObjectName('_repr_svg_') |
|
731 | 740 | |
|
732 | 741 | |
|
733 | 742 | class PNGFormatter(BaseFormatter): |
|
734 | 743 | """A PNG formatter. |
|
735 | 744 | |
|
736 | 745 | To define the callables that compute the PNG representation of your |
|
737 | 746 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
738 | 747 | or :meth:`for_type_by_name` methods to register functions that handle |
|
739 | 748 | this. |
|
740 | 749 | |
|
741 | 750 | The return value of this formatter should be raw PNG data, *not* |
|
742 | 751 | base64 encoded. |
|
743 | 752 | """ |
|
744 | 753 | format_type = Unicode('image/png') |
|
745 | 754 | |
|
746 | 755 | print_method = ObjectName('_repr_png_') |
|
747 | 756 | |
|
748 | 757 | _return_type = (bytes, unicode_type) |
|
749 | 758 | |
|
750 | 759 | |
|
751 | 760 | class JPEGFormatter(BaseFormatter): |
|
752 | 761 | """A JPEG formatter. |
|
753 | 762 | |
|
754 | 763 | To define the callables that compute the JPEG representation of your |
|
755 | 764 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
756 | 765 | or :meth:`for_type_by_name` methods to register functions that handle |
|
757 | 766 | this. |
|
758 | 767 | |
|
759 | 768 | The return value of this formatter should be raw JPEG data, *not* |
|
760 | 769 | base64 encoded. |
|
761 | 770 | """ |
|
762 | 771 | format_type = Unicode('image/jpeg') |
|
763 | 772 | |
|
764 | 773 | print_method = ObjectName('_repr_jpeg_') |
|
765 | 774 | |
|
766 | 775 | _return_type = (bytes, unicode_type) |
|
767 | 776 | |
|
768 | 777 | |
|
769 | 778 | class LatexFormatter(BaseFormatter): |
|
770 | 779 | """A LaTeX formatter. |
|
771 | 780 | |
|
772 | 781 | To define the callables that compute the LaTeX representation of your |
|
773 | 782 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
774 | 783 | or :meth:`for_type_by_name` methods to register functions that handle |
|
775 | 784 | this. |
|
776 | 785 | |
|
777 | 786 | The return value of this formatter should be a valid LaTeX equation, |
|
778 | 787 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
779 | 788 | environment. |
|
780 | 789 | """ |
|
781 | 790 | format_type = Unicode('text/latex') |
|
782 | 791 | |
|
783 | 792 | print_method = ObjectName('_repr_latex_') |
|
784 | 793 | |
|
785 | 794 | |
|
786 | 795 | class JSONFormatter(BaseFormatter): |
|
787 | 796 | """A JSON string formatter. |
|
788 | 797 | |
|
789 | 798 | To define the callables that compute the JSON string representation of |
|
790 | 799 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
791 | 800 | or :meth:`for_type_by_name` methods to register functions that handle |
|
792 | 801 | this. |
|
793 | 802 | |
|
794 | 803 | The return value of this formatter should be a valid JSON string. |
|
795 | 804 | """ |
|
796 | 805 | format_type = Unicode('application/json') |
|
797 | 806 | |
|
798 | 807 | print_method = ObjectName('_repr_json_') |
|
799 | 808 | |
|
800 | 809 | |
|
801 | 810 | class JavascriptFormatter(BaseFormatter): |
|
802 | 811 | """A Javascript formatter. |
|
803 | 812 | |
|
804 | 813 | To define the callables that compute the Javascript representation of |
|
805 | 814 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
806 | 815 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
807 | 816 | that handle this. |
|
808 | 817 | |
|
809 | 818 | The return value of this formatter should be valid Javascript code and |
|
810 | 819 | should *not* be enclosed in ```<script>``` tags. |
|
811 | 820 | """ |
|
812 | 821 | format_type = Unicode('application/javascript') |
|
813 | 822 | |
|
814 | 823 | print_method = ObjectName('_repr_javascript_') |
|
815 | 824 | |
|
816 | 825 | |
|
817 | 826 | class PDFFormatter(BaseFormatter): |
|
818 | 827 | """A PDF formatter. |
|
819 | 828 | |
|
820 | 829 | To define the callables that compute the PDF representation of your |
|
821 | 830 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` |
|
822 | 831 | or :meth:`for_type_by_name` methods to register functions that handle |
|
823 | 832 | this. |
|
824 | 833 | |
|
825 | 834 | The return value of this formatter should be raw PDF data, *not* |
|
826 | 835 | base64 encoded. |
|
827 | 836 | """ |
|
828 | 837 | format_type = Unicode('application/pdf') |
|
829 | 838 | |
|
830 | 839 | print_method = ObjectName('_repr_pdf_') |
|
831 | 840 | |
|
832 | 841 | _return_type = (bytes, unicode_type) |
|
833 | 842 | |
|
843 | class SelfDisplayingFormatter(BaseFormatter): | |
|
844 | """A Formatter for objects that know how to display themselves. | |
|
845 | ||
|
846 | To define the callables that compute the representation of your | |
|
847 | objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` | |
|
848 | or :meth:`for_type_by_name` methods to register functions that handle | |
|
849 | this. Unlike mime-type displays, this method should not return anything, | |
|
850 | instead calling any appropriate display methods itself. | |
|
851 | ||
|
852 | This display formatter has highest priority. | |
|
853 | If it fires, no other display formatter will be called. | |
|
854 | """ | |
|
855 | print_method = ObjectName('_ipython_display_') | |
|
856 | _return_type = (type(None), bool) | |
|
857 | ||
|
858 | ||
|
859 | @warn_format_error | |
|
860 | def __call__(self, obj): | |
|
861 | """Compute the format for an object.""" | |
|
862 | if self.enabled: | |
|
863 | # lookup registered printer | |
|
864 | try: | |
|
865 | printer = self.lookup(obj) | |
|
866 | except KeyError: | |
|
867 | pass | |
|
868 | else: | |
|
869 | printer(obj) | |
|
870 | return True | |
|
871 | # Finally look for special method names | |
|
872 | method = _safe_get_formatter_method(obj, self.print_method) | |
|
873 | if method is not None: | |
|
874 | method() | |
|
875 | return True | |
|
876 | ||
|
834 | 877 | |
|
835 | 878 | FormatterABC.register(BaseFormatter) |
|
836 | 879 | FormatterABC.register(PlainTextFormatter) |
|
837 | 880 | FormatterABC.register(HTMLFormatter) |
|
838 | 881 | FormatterABC.register(MarkdownFormatter) |
|
839 | 882 | FormatterABC.register(SVGFormatter) |
|
840 | 883 | FormatterABC.register(PNGFormatter) |
|
841 | 884 | FormatterABC.register(PDFFormatter) |
|
842 | 885 | FormatterABC.register(JPEGFormatter) |
|
843 | 886 | FormatterABC.register(LatexFormatter) |
|
844 | 887 | FormatterABC.register(JSONFormatter) |
|
845 | 888 | FormatterABC.register(JavascriptFormatter) |
|
889 | FormatterABC.register(SelfDisplayingFormatter) | |
|
846 | 890 | |
|
847 | 891 | |
|
848 | 892 | def format_display_data(obj, include=None, exclude=None): |
|
849 | 893 | """Return a format data dict for an object. |
|
850 | 894 | |
|
851 | 895 | By default all format types will be computed. |
|
852 | 896 | |
|
853 | 897 | The following MIME types are currently implemented: |
|
854 | 898 | |
|
855 | 899 | * text/plain |
|
856 | 900 | * text/html |
|
857 | 901 | * text/markdown |
|
858 | 902 | * text/latex |
|
859 | 903 | * application/json |
|
860 | 904 | * application/javascript |
|
861 | 905 | * application/pdf |
|
862 | 906 | * image/png |
|
863 | 907 | * image/jpeg |
|
864 | 908 | * image/svg+xml |
|
865 | 909 | |
|
866 | 910 | Parameters |
|
867 | 911 | ---------- |
|
868 | 912 | obj : object |
|
869 | 913 | The Python object whose format data will be computed. |
|
870 | 914 | |
|
871 | 915 | Returns |
|
872 | 916 | ------- |
|
873 | 917 | format_dict : dict |
|
874 | 918 | A dictionary of key/value pairs, one or each format that was |
|
875 | 919 | generated for the object. The keys are the format types, which |
|
876 | 920 | will usually be MIME type strings and the values and JSON'able |
|
877 | 921 | data structure containing the raw data for the representation in |
|
878 | 922 | that format. |
|
879 | 923 | include : list or tuple, optional |
|
880 | 924 | A list of format type strings (MIME types) to include in the |
|
881 | 925 | format data dict. If this is set *only* the format types included |
|
882 | 926 | in this list will be computed. |
|
883 | 927 | exclude : list or tuple, optional |
|
884 | 928 | A list of format type string (MIME types) to exclue in the format |
|
885 | 929 | data dict. If this is set all format types will be computed, |
|
886 | 930 | except for those included in this argument. |
|
887 | 931 | """ |
|
888 | 932 | from IPython.core.interactiveshell import InteractiveShell |
|
889 | 933 | |
|
890 | 934 | InteractiveShell.instance().display_formatter.format( |
|
891 | 935 | obj, |
|
892 | 936 | include, |
|
893 | 937 | exclude |
|
894 | 938 | ) |
|
895 | 939 |
General Comments 0
You need to be logged in to leave comments.
Login now