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