##// END OF EJS Templates
Fix 'Custom Display Logic' example notebook for Python 3
Thomas Kluyver -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,556 +1,558 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) 2008-2011 The IPython Development Team
10 # Copyright (C) 2008-2011 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 from xml.dom import minidom
22 from xml.dom import minidom
23
23
24 from .displaypub import (
24 from .displaypub import (
25 publish_pretty, publish_html,
25 publish_pretty, publish_html,
26 publish_latex, publish_svg,
26 publish_latex, publish_svg,
27 publish_png, publish_json,
27 publish_png, publish_json,
28 publish_javascript, publish_jpeg
28 publish_javascript, publish_jpeg
29 )
29 )
30
30
31 from IPython.utils.py3compat import string_types
32
31 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
32 # Main functions
34 # Main functions
33 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
34
36
35 def display(*objs, **kwargs):
37 def display(*objs, **kwargs):
36 """Display a Python object in all frontends.
38 """Display a Python object in all frontends.
37
39
38 By default all representations will be computed and sent to the frontends.
40 By default all representations will be computed and sent to the frontends.
39 Frontends can decide which representation is used and how.
41 Frontends can decide which representation is used and how.
40
42
41 Parameters
43 Parameters
42 ----------
44 ----------
43 objs : tuple of objects
45 objs : tuple of objects
44 The Python objects to display.
46 The Python objects to display.
45 include : list or tuple, optional
47 include : list or tuple, optional
46 A list of format type strings (MIME types) to include in the
48 A list of format type strings (MIME types) to include in the
47 format data dict. If this is set *only* the format types included
49 format data dict. If this is set *only* the format types included
48 in this list will be computed.
50 in this list will be computed.
49 exclude : list or tuple, optional
51 exclude : list or tuple, optional
50 A list of format type string (MIME types) to exclue in the format
52 A list of format type string (MIME types) to exclue in the format
51 data dict. If this is set all format types will be computed,
53 data dict. If this is set all format types will be computed,
52 except for those included in this argument.
54 except for those included in this argument.
53 """
55 """
54 include = kwargs.get('include')
56 include = kwargs.get('include')
55 exclude = kwargs.get('exclude')
57 exclude = kwargs.get('exclude')
56
58
57 from IPython.core.interactiveshell import InteractiveShell
59 from IPython.core.interactiveshell import InteractiveShell
58 inst = InteractiveShell.instance()
60 inst = InteractiveShell.instance()
59 format = inst.display_formatter.format
61 format = inst.display_formatter.format
60 publish = inst.display_pub.publish
62 publish = inst.display_pub.publish
61
63
62 for obj in objs:
64 for obj in objs:
63 format_dict = format(obj, include=include, exclude=exclude)
65 format_dict = format(obj, include=include, exclude=exclude)
64 publish('IPython.core.display.display', format_dict)
66 publish('IPython.core.display.display', format_dict)
65
67
66
68
67 def display_pretty(*objs, **kwargs):
69 def display_pretty(*objs, **kwargs):
68 """Display the pretty (default) representation of an object.
70 """Display the pretty (default) representation of an object.
69
71
70 Parameters
72 Parameters
71 ----------
73 ----------
72 objs : tuple of objects
74 objs : tuple of objects
73 The Python objects to display, or if raw=True raw text data to
75 The Python objects to display, or if raw=True raw text data to
74 display.
76 display.
75 raw : bool
77 raw : bool
76 Are the data objects raw data or Python objects that need to be
78 Are the data objects raw data or Python objects that need to be
77 formatted before display? [default: False]
79 formatted before display? [default: False]
78 """
80 """
79 raw = kwargs.pop('raw',False)
81 raw = kwargs.pop('raw',False)
80 if raw:
82 if raw:
81 for obj in objs:
83 for obj in objs:
82 publish_pretty(obj)
84 publish_pretty(obj)
83 else:
85 else:
84 display(*objs, include=['text/plain'])
86 display(*objs, include=['text/plain'])
85
87
86
88
87 def display_html(*objs, **kwargs):
89 def display_html(*objs, **kwargs):
88 """Display the HTML representation of an object.
90 """Display the HTML representation of an object.
89
91
90 Parameters
92 Parameters
91 ----------
93 ----------
92 objs : tuple of objects
94 objs : tuple of objects
93 The Python objects to display, or if raw=True raw HTML data to
95 The Python objects to display, or if raw=True raw HTML data to
94 display.
96 display.
95 raw : bool
97 raw : bool
96 Are the data objects raw data or Python objects that need to be
98 Are the data objects raw data or Python objects that need to be
97 formatted before display? [default: False]
99 formatted before display? [default: False]
98 """
100 """
99 raw = kwargs.pop('raw',False)
101 raw = kwargs.pop('raw',False)
100 if raw:
102 if raw:
101 for obj in objs:
103 for obj in objs:
102 publish_html(obj)
104 publish_html(obj)
103 else:
105 else:
104 display(*objs, include=['text/plain','text/html'])
106 display(*objs, include=['text/plain','text/html'])
105
107
106
108
107 def display_svg(*objs, **kwargs):
109 def display_svg(*objs, **kwargs):
108 """Display the SVG representation of an object.
110 """Display the SVG representation of an object.
109
111
110 Parameters
112 Parameters
111 ----------
113 ----------
112 objs : tuple of objects
114 objs : tuple of objects
113 The Python objects to display, or if raw=True raw svg data to
115 The Python objects to display, or if raw=True raw svg data to
114 display.
116 display.
115 raw : bool
117 raw : bool
116 Are the data objects raw data or Python objects that need to be
118 Are the data objects raw data or Python objects that need to be
117 formatted before display? [default: False]
119 formatted before display? [default: False]
118 """
120 """
119 raw = kwargs.pop('raw',False)
121 raw = kwargs.pop('raw',False)
120 if raw:
122 if raw:
121 for obj in objs:
123 for obj in objs:
122 publish_svg(obj)
124 publish_svg(obj)
123 else:
125 else:
124 display(*objs, include=['text/plain','image/svg+xml'])
126 display(*objs, include=['text/plain','image/svg+xml'])
125
127
126
128
127 def display_png(*objs, **kwargs):
129 def display_png(*objs, **kwargs):
128 """Display the PNG representation of an object.
130 """Display the PNG representation of an object.
129
131
130 Parameters
132 Parameters
131 ----------
133 ----------
132 objs : tuple of objects
134 objs : tuple of objects
133 The Python objects to display, or if raw=True raw png data to
135 The Python objects to display, or if raw=True raw png data to
134 display.
136 display.
135 raw : bool
137 raw : bool
136 Are the data objects raw data or Python objects that need to be
138 Are the data objects raw data or Python objects that need to be
137 formatted before display? [default: False]
139 formatted before display? [default: False]
138 """
140 """
139 raw = kwargs.pop('raw',False)
141 raw = kwargs.pop('raw',False)
140 if raw:
142 if raw:
141 for obj in objs:
143 for obj in objs:
142 publish_png(obj)
144 publish_png(obj)
143 else:
145 else:
144 display(*objs, include=['text/plain','image/png'])
146 display(*objs, include=['text/plain','image/png'])
145
147
146
148
147 def display_jpeg(*objs, **kwargs):
149 def display_jpeg(*objs, **kwargs):
148 """Display the JPEG representation of an object.
150 """Display the JPEG representation of an object.
149
151
150 Parameters
152 Parameters
151 ----------
153 ----------
152 objs : tuple of objects
154 objs : tuple of objects
153 The Python objects to display, or if raw=True raw JPEG data to
155 The Python objects to display, or if raw=True raw JPEG data to
154 display.
156 display.
155 raw : bool
157 raw : bool
156 Are the data objects raw data or Python objects that need to be
158 Are the data objects raw data or Python objects that need to be
157 formatted before display? [default: False]
159 formatted before display? [default: False]
158 """
160 """
159 raw = kwargs.pop('raw',False)
161 raw = kwargs.pop('raw',False)
160 if raw:
162 if raw:
161 for obj in objs:
163 for obj in objs:
162 publish_jpeg(obj)
164 publish_jpeg(obj)
163 else:
165 else:
164 display(*objs, include=['text/plain','image/jpeg'])
166 display(*objs, include=['text/plain','image/jpeg'])
165
167
166
168
167 def display_latex(*objs, **kwargs):
169 def display_latex(*objs, **kwargs):
168 """Display the LaTeX representation of an object.
170 """Display the LaTeX representation of an object.
169
171
170 Parameters
172 Parameters
171 ----------
173 ----------
172 objs : tuple of objects
174 objs : tuple of objects
173 The Python objects to display, or if raw=True raw latex data to
175 The Python objects to display, or if raw=True raw latex data to
174 display.
176 display.
175 raw : bool
177 raw : bool
176 Are the data objects raw data or Python objects that need to be
178 Are the data objects raw data or Python objects that need to be
177 formatted before display? [default: False]
179 formatted before display? [default: False]
178 """
180 """
179 raw = kwargs.pop('raw',False)
181 raw = kwargs.pop('raw',False)
180 if raw:
182 if raw:
181 for obj in objs:
183 for obj in objs:
182 publish_latex(obj)
184 publish_latex(obj)
183 else:
185 else:
184 display(*objs, include=['text/plain','text/latex'])
186 display(*objs, include=['text/plain','text/latex'])
185
187
186
188
187 def display_json(*objs, **kwargs):
189 def display_json(*objs, **kwargs):
188 """Display the JSON representation of an object.
190 """Display the JSON representation of an object.
189
191
190 Note that not many frontends support displaying JSON.
192 Note that not many frontends support displaying JSON.
191
193
192 Parameters
194 Parameters
193 ----------
195 ----------
194 objs : tuple of objects
196 objs : tuple of objects
195 The Python objects to display, or if raw=True raw json data to
197 The Python objects to display, or if raw=True raw json data to
196 display.
198 display.
197 raw : bool
199 raw : bool
198 Are the data objects raw data or Python objects that need to be
200 Are the data objects raw data or Python objects that need to be
199 formatted before display? [default: False]
201 formatted before display? [default: False]
200 """
202 """
201 raw = kwargs.pop('raw',False)
203 raw = kwargs.pop('raw',False)
202 if raw:
204 if raw:
203 for obj in objs:
205 for obj in objs:
204 publish_json(obj)
206 publish_json(obj)
205 else:
207 else:
206 display(*objs, include=['text/plain','application/json'])
208 display(*objs, include=['text/plain','application/json'])
207
209
208
210
209 def display_javascript(*objs, **kwargs):
211 def display_javascript(*objs, **kwargs):
210 """Display the Javascript representation of an object.
212 """Display the Javascript representation of an object.
211
213
212 Parameters
214 Parameters
213 ----------
215 ----------
214 objs : tuple of objects
216 objs : tuple of objects
215 The Python objects to display, or if raw=True raw javascript data to
217 The Python objects to display, or if raw=True raw javascript data to
216 display.
218 display.
217 raw : bool
219 raw : bool
218 Are the data objects raw data or Python objects that need to be
220 Are the data objects raw data or Python objects that need to be
219 formatted before display? [default: False]
221 formatted before display? [default: False]
220 """
222 """
221 raw = kwargs.pop('raw',False)
223 raw = kwargs.pop('raw',False)
222 if raw:
224 if raw:
223 for obj in objs:
225 for obj in objs:
224 publish_javascript(obj)
226 publish_javascript(obj)
225 else:
227 else:
226 display(*objs, include=['text/plain','application/javascript'])
228 display(*objs, include=['text/plain','application/javascript'])
227
229
228 #-----------------------------------------------------------------------------
230 #-----------------------------------------------------------------------------
229 # Smart classes
231 # Smart classes
230 #-----------------------------------------------------------------------------
232 #-----------------------------------------------------------------------------
231
233
232
234
233 class DisplayObject(object):
235 class DisplayObject(object):
234 """An object that wraps data to be displayed."""
236 """An object that wraps data to be displayed."""
235
237
236 _read_flags = 'r'
238 _read_flags = 'r'
237
239
238 def __init__(self, data=None, url=None, filename=None):
240 def __init__(self, data=None, url=None, filename=None):
239 """Create a display object given raw data.
241 """Create a display object given raw data.
240
242
241 When this object is returned by an expression or passed to the
243 When this object is returned by an expression or passed to the
242 display function, it will result in the data being displayed
244 display function, it will result in the data being displayed
243 in the frontend. The MIME type of the data should match the
245 in the frontend. The MIME type of the data should match the
244 subclasses used, so the Png subclass should be used for 'image/png'
246 subclasses used, so the Png subclass should be used for 'image/png'
245 data. If the data is a URL, the data will first be downloaded
247 data. If the data is a URL, the data will first be downloaded
246 and then displayed. If
248 and then displayed. If
247
249
248 Parameters
250 Parameters
249 ----------
251 ----------
250 data : unicode, str or bytes
252 data : unicode, str or bytes
251 The raw data or a URL to download the data from.
253 The raw data or a URL to download the data from.
252 url : unicode
254 url : unicode
253 A URL to download the data from.
255 A URL to download the data from.
254 filename : unicode
256 filename : unicode
255 Path to a local file to load the data from.
257 Path to a local file to load the data from.
256 """
258 """
257 if data is not None and data.startswith('http'):
259 if data is not None and isinstance(data, string_types) and data.startswith('http'):
258 self.url = data
260 self.url = data
259 self.filename = None
261 self.filename = None
260 self.data = None
262 self.data = None
261 else:
263 else:
262 self.data = data
264 self.data = data
263 self.url = url
265 self.url = url
264 self.filename = None if filename is None else unicode(filename)
266 self.filename = None if filename is None else unicode(filename)
265 self.reload()
267 self.reload()
266
268
267 def reload(self):
269 def reload(self):
268 """Reload the raw data from file or URL."""
270 """Reload the raw data from file or URL."""
269 if self.filename is not None:
271 if self.filename is not None:
270 with open(self.filename, self._read_flags) as f:
272 with open(self.filename, self._read_flags) as f:
271 self.data = f.read()
273 self.data = f.read()
272 elif self.url is not None:
274 elif self.url is not None:
273 try:
275 try:
274 import urllib2
276 import urllib2
275 response = urllib2.urlopen(self.url)
277 response = urllib2.urlopen(self.url)
276 self.data = response.read()
278 self.data = response.read()
277 # extract encoding from header, if there is one:
279 # extract encoding from header, if there is one:
278 encoding = None
280 encoding = None
279 for sub in response.headers['content-type'].split(';'):
281 for sub in response.headers['content-type'].split(';'):
280 sub = sub.strip()
282 sub = sub.strip()
281 if sub.startswith('charset'):
283 if sub.startswith('charset'):
282 encoding = sub.split('=')[-1].strip()
284 encoding = sub.split('=')[-1].strip()
283 break
285 break
284 # decode data, if an encoding was specified
286 # decode data, if an encoding was specified
285 if encoding:
287 if encoding:
286 self.data = self.data.decode(encoding, 'replace')
288 self.data = self.data.decode(encoding, 'replace')
287 except:
289 except:
288 self.data = None
290 self.data = None
289
291
290 class Pretty(DisplayObject):
292 class Pretty(DisplayObject):
291
293
292 def _repr_pretty_(self):
294 def _repr_pretty_(self):
293 return self.data
295 return self.data
294
296
295
297
296 class HTML(DisplayObject):
298 class HTML(DisplayObject):
297
299
298 def _repr_html_(self):
300 def _repr_html_(self):
299 return self.data
301 return self.data
300
302
301
303
302 class Math(DisplayObject):
304 class Math(DisplayObject):
303
305
304 def _repr_latex_(self):
306 def _repr_latex_(self):
305 s = self.data.strip('$')
307 s = self.data.strip('$')
306 return "$$%s$$" % s
308 return "$$%s$$" % s
307
309
308
310
309 class Latex(DisplayObject):
311 class Latex(DisplayObject):
310
312
311 def _repr_latex_(self):
313 def _repr_latex_(self):
312 return self.data
314 return self.data
313
315
314
316
315 class SVG(DisplayObject):
317 class SVG(DisplayObject):
316
318
317 # wrap data in a property, which extracts the <svg> tag, discarding
319 # wrap data in a property, which extracts the <svg> tag, discarding
318 # document headers
320 # document headers
319 _data = None
321 _data = None
320
322
321 @property
323 @property
322 def data(self):
324 def data(self):
323 return self._data
325 return self._data
324
326
325 @data.setter
327 @data.setter
326 def data(self, svg):
328 def data(self, svg):
327 if svg is None:
329 if svg is None:
328 self._data = None
330 self._data = None
329 return
331 return
330 # parse into dom object
332 # parse into dom object
331 x = minidom.parseString(svg)
333 x = minidom.parseString(svg)
332 # get svg tag (should be 1)
334 # get svg tag (should be 1)
333 found_svg = x.getElementsByTagName('svg')
335 found_svg = x.getElementsByTagName('svg')
334 if found_svg:
336 if found_svg:
335 svg = found_svg[0].toxml()
337 svg = found_svg[0].toxml()
336 else:
338 else:
337 # fallback on the input, trust the user
339 # fallback on the input, trust the user
338 # but this is probably an error.
340 # but this is probably an error.
339 pass
341 pass
340 self._data = svg
342 self._data = svg
341
343
342 def _repr_svg_(self):
344 def _repr_svg_(self):
343 return self.data
345 return self.data
344
346
345
347
346 class JSON(DisplayObject):
348 class JSON(DisplayObject):
347
349
348 def _repr_json_(self):
350 def _repr_json_(self):
349 return self.data
351 return self.data
350
352
351 css_t = """$("head").append($("<link/>").attr({
353 css_t = """$("head").append($("<link/>").attr({
352 rel: "stylesheet",
354 rel: "stylesheet",
353 type: "text/css",
355 type: "text/css",
354 href: "%s"
356 href: "%s"
355 }));
357 }));
356 """
358 """
357
359
358 lib_t1 = """$.getScript("%s", function () {
360 lib_t1 = """$.getScript("%s", function () {
359 """
361 """
360 lib_t2 = """});
362 lib_t2 = """});
361 """
363 """
362
364
363 class Javascript(DisplayObject):
365 class Javascript(DisplayObject):
364
366
365 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
367 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
366 """Create a Javascript display object given raw data.
368 """Create a Javascript display object given raw data.
367
369
368 When this object is returned by an expression or passed to the
370 When this object is returned by an expression or passed to the
369 display function, it will result in the data being displayed
371 display function, it will result in the data being displayed
370 in the frontend. If the data is a URL, the data will first be
372 in the frontend. If the data is a URL, the data will first be
371 downloaded and then displayed.
373 downloaded and then displayed.
372
374
373 In the Notebook, the containing element will be available as `element`,
375 In the Notebook, the containing element will be available as `element`,
374 and jQuery will be available. The output area starts hidden, so if
376 and jQuery will be available. The output area starts hidden, so if
375 the js appends content to `element` that should be visible, then
377 the js appends content to `element` that should be visible, then
376 it must call `container.show()` to unhide the area.
378 it must call `container.show()` to unhide the area.
377
379
378 Parameters
380 Parameters
379 ----------
381 ----------
380 data : unicode, str or bytes
382 data : unicode, str or bytes
381 The Javascript source code or a URL to download it from.
383 The Javascript source code or a URL to download it from.
382 url : unicode
384 url : unicode
383 A URL to download the data from.
385 A URL to download the data from.
384 filename : unicode
386 filename : unicode
385 Path to a local file to load the data from.
387 Path to a local file to load the data from.
386 lib : list or str
388 lib : list or str
387 A sequence of Javascript library URLs to load asynchronously before
389 A sequence of Javascript library URLs to load asynchronously before
388 running the source code. The full URLs of the libraries should
390 running the source code. The full URLs of the libraries should
389 be given. A single Javascript library URL can also be given as a
391 be given. A single Javascript library URL can also be given as a
390 string.
392 string.
391 css: : list or str
393 css: : list or str
392 A sequence of css files to load before running the source code.
394 A sequence of css files to load before running the source code.
393 The full URLs of the css files should be give. A single css URL
395 The full URLs of the css files should be give. A single css URL
394 can also be given as a string.
396 can also be given as a string.
395 """
397 """
396 if isinstance(lib, basestring):
398 if isinstance(lib, basestring):
397 lib = [lib]
399 lib = [lib]
398 elif lib is None:
400 elif lib is None:
399 lib = []
401 lib = []
400 if isinstance(css, basestring):
402 if isinstance(css, basestring):
401 css = [css]
403 css = [css]
402 elif css is None:
404 elif css is None:
403 css = []
405 css = []
404 if not isinstance(lib, (list,tuple)):
406 if not isinstance(lib, (list,tuple)):
405 raise TypeError('expected sequence, got: %r' % lib)
407 raise TypeError('expected sequence, got: %r' % lib)
406 if not isinstance(css, (list,tuple)):
408 if not isinstance(css, (list,tuple)):
407 raise TypeError('expected sequence, got: %r' % css)
409 raise TypeError('expected sequence, got: %r' % css)
408 self.lib = lib
410 self.lib = lib
409 self.css = css
411 self.css = css
410 super(Javascript, self).__init__(data=data, url=url, filename=filename)
412 super(Javascript, self).__init__(data=data, url=url, filename=filename)
411
413
412 def _repr_javascript_(self):
414 def _repr_javascript_(self):
413 r = ''
415 r = ''
414 for c in self.css:
416 for c in self.css:
415 r += css_t % c
417 r += css_t % c
416 for l in self.lib:
418 for l in self.lib:
417 r += lib_t1 % l
419 r += lib_t1 % l
418 r += self.data
420 r += self.data
419 r += lib_t2*len(self.lib)
421 r += lib_t2*len(self.lib)
420 return r
422 return r
421
423
422
424
423 class Image(DisplayObject):
425 class Image(DisplayObject):
424
426
425 _read_flags = 'rb'
427 _read_flags = 'rb'
426 _FMT_JPEG = u'jpeg'
428 _FMT_JPEG = u'jpeg'
427 _FMT_PNG = u'png'
429 _FMT_PNG = u'png'
428 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
430 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
429
431
430 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None):
432 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None):
431 """Create a display an PNG/JPEG image given raw data.
433 """Create a display an PNG/JPEG image given raw data.
432
434
433 When this object is returned by an expression or passed to the
435 When this object is returned by an expression or passed to the
434 display function, it will result in the image being displayed
436 display function, it will result in the image being displayed
435 in the frontend.
437 in the frontend.
436
438
437 Parameters
439 Parameters
438 ----------
440 ----------
439 data : unicode, str or bytes
441 data : unicode, str or bytes
440 The raw data or a URL to download the data from.
442 The raw data or a URL to download the data from.
441 url : unicode
443 url : unicode
442 A URL to download the data from.
444 A URL to download the data from.
443 filename : unicode
445 filename : unicode
444 Path to a local file to load the data from.
446 Path to a local file to load the data from.
445 format : unicode
447 format : unicode
446 The format of the image data (png/jpeg/jpg). If a filename or URL is given
448 The format of the image data (png/jpeg/jpg). If a filename or URL is given
447 for format will be inferred from the filename extension.
449 for format will be inferred from the filename extension.
448 embed : bool
450 embed : bool
449 Should the image data be embedded using a data URI (True) or be
451 Should the image data be embedded using a data URI (True) or be
450 loaded using an <img> tag. Set this to True if you want the image
452 loaded using an <img> tag. Set this to True if you want the image
451 to be viewable later with no internet connection in the notebook.
453 to be viewable later with no internet connection in the notebook.
452
454
453 Default is `True`, unless the keyword argument `url` is set, then
455 Default is `True`, unless the keyword argument `url` is set, then
454 default value is `False`.
456 default value is `False`.
455
457
456 Note that QtConsole is not able to display images if `embed` is set to `False`
458 Note that QtConsole is not able to display images if `embed` is set to `False`
457 width : int
459 width : int
458 Width to which to constrain the image in html
460 Width to which to constrain the image in html
459 height : int
461 height : int
460 Height to which to constrain the image in html
462 Height to which to constrain the image in html
461
463
462 Examples
464 Examples
463 --------
465 --------
464 # embed implicitly True, works in qtconsole and notebook
466 # embed implicitly True, works in qtconsole and notebook
465 Image('http://www.google.fr/images/srpr/logo3w.png')
467 Image('http://www.google.fr/images/srpr/logo3w.png')
466
468
467 # embed implicitly False, does not works in qtconsole but works in notebook if
469 # embed implicitly False, does not works in qtconsole but works in notebook if
468 # internet connection available
470 # internet connection available
469 Image(url='http://www.google.fr/images/srpr/logo3w.png')
471 Image(url='http://www.google.fr/images/srpr/logo3w.png')
470
472
471 """
473 """
472 if filename is not None:
474 if filename is not None:
473 ext = self._find_ext(filename)
475 ext = self._find_ext(filename)
474 elif url is not None:
476 elif url is not None:
475 ext = self._find_ext(url)
477 ext = self._find_ext(url)
476 elif data is None:
478 elif data is None:
477 raise ValueError("No image data found. Expecting filename, url, or data.")
479 raise ValueError("No image data found. Expecting filename, url, or data.")
478 elif data.startswith('http'):
480 elif isinstance(data, string_types) and data.startswith('http'):
479 ext = self._find_ext(data)
481 ext = self._find_ext(data)
480 else:
482 else:
481 ext = None
483 ext = None
482
484
483 if ext is not None:
485 if ext is not None:
484 format = ext.lower()
486 format = ext.lower()
485 if ext == u'jpg' or ext == u'jpeg':
487 if ext == u'jpg' or ext == u'jpeg':
486 format = self._FMT_JPEG
488 format = self._FMT_JPEG
487 if ext == u'png':
489 if ext == u'png':
488 format = self._FMT_PNG
490 format = self._FMT_PNG
489
491
490 self.format = unicode(format).lower()
492 self.format = unicode(format).lower()
491 self.embed = embed if embed is not None else (url is None)
493 self.embed = embed if embed is not None else (url is None)
492
494
493 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
495 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
494 raise ValueError("Cannot embed the '%s' image format" % (self.format))
496 raise ValueError("Cannot embed the '%s' image format" % (self.format))
495 self.width = width
497 self.width = width
496 self.height = height
498 self.height = height
497 super(Image, self).__init__(data=data, url=url, filename=filename)
499 super(Image, self).__init__(data=data, url=url, filename=filename)
498
500
499 def reload(self):
501 def reload(self):
500 """Reload the raw data from file or URL."""
502 """Reload the raw data from file or URL."""
501 if self.embed:
503 if self.embed:
502 super(Image,self).reload()
504 super(Image,self).reload()
503
505
504 def _repr_html_(self):
506 def _repr_html_(self):
505 if not self.embed:
507 if not self.embed:
506 width = height = ''
508 width = height = ''
507 if self.width:
509 if self.width:
508 width = ' width="%d"' % self.width
510 width = ' width="%d"' % self.width
509 if self.height:
511 if self.height:
510 height = ' height="%d"' % self.height
512 height = ' height="%d"' % self.height
511 return u'<img src="%s"%s%s/>' % (self.url, width, height)
513 return u'<img src="%s"%s%s/>' % (self.url, width, height)
512
514
513 def _repr_png_(self):
515 def _repr_png_(self):
514 if self.embed and self.format == u'png':
516 if self.embed and self.format == u'png':
515 return self.data
517 return self.data
516
518
517 def _repr_jpeg_(self):
519 def _repr_jpeg_(self):
518 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
520 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
519 return self.data
521 return self.data
520
522
521 def _find_ext(self, s):
523 def _find_ext(self, s):
522 return unicode(s.split('.')[-1].lower())
524 return unicode(s.split('.')[-1].lower())
523
525
524
526
525 def clear_output(stdout=True, stderr=True, other=True):
527 def clear_output(stdout=True, stderr=True, other=True):
526 """Clear the output of the current cell receiving output.
528 """Clear the output of the current cell receiving output.
527
529
528 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
530 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
529 produced by display()) can be excluded from the clear event.
531 produced by display()) can be excluded from the clear event.
530
532
531 By default, everything is cleared.
533 By default, everything is cleared.
532
534
533 Parameters
535 Parameters
534 ----------
536 ----------
535 stdout : bool [default: True]
537 stdout : bool [default: True]
536 Whether to clear stdout.
538 Whether to clear stdout.
537 stderr : bool [default: True]
539 stderr : bool [default: True]
538 Whether to clear stderr.
540 Whether to clear stderr.
539 other : bool [default: True]
541 other : bool [default: True]
540 Whether to clear everything else that is not stdout/stderr
542 Whether to clear everything else that is not stdout/stderr
541 (e.g. figures,images,HTML, any result of display()).
543 (e.g. figures,images,HTML, any result of display()).
542 """
544 """
543 from IPython.core.interactiveshell import InteractiveShell
545 from IPython.core.interactiveshell import InteractiveShell
544 if InteractiveShell.initialized():
546 if InteractiveShell.initialized():
545 InteractiveShell.instance().display_pub.clear_output(
547 InteractiveShell.instance().display_pub.clear_output(
546 stdout=stdout, stderr=stderr, other=other,
548 stdout=stdout, stderr=stderr, other=other,
547 )
549 )
548 else:
550 else:
549 from IPython.utils import io
551 from IPython.utils import io
550 if stdout:
552 if stdout:
551 print('\033[2K\r', file=io.stdout, end='')
553 print('\033[2K\r', file=io.stdout, end='')
552 io.stdout.flush()
554 io.stdout.flush()
553 if stderr:
555 if stderr:
554 print('\033[2K\r', file=io.stderr, end='')
556 print('\033[2K\r', file=io.stderr, end='')
555 io.stderr.flush()
557 io.stderr.flush()
556
558
@@ -1,179 +1,183 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 import __builtin__
3 import __builtin__
4 import functools
4 import functools
5 import sys
5 import sys
6 import re
6 import re
7 import types
7 import types
8
8
9 from .encoding import DEFAULT_ENCODING
9 from .encoding import DEFAULT_ENCODING
10
10
11 orig_open = open
11 orig_open = open
12
12
13 def no_code(x, encoding=None):
13 def no_code(x, encoding=None):
14 return x
14 return x
15
15
16 def decode(s, encoding=None):
16 def decode(s, encoding=None):
17 encoding = encoding or DEFAULT_ENCODING
17 encoding = encoding or DEFAULT_ENCODING
18 return s.decode(encoding, "replace")
18 return s.decode(encoding, "replace")
19
19
20 def encode(u, encoding=None):
20 def encode(u, encoding=None):
21 encoding = encoding or DEFAULT_ENCODING
21 encoding = encoding or DEFAULT_ENCODING
22 return u.encode(encoding, "replace")
22 return u.encode(encoding, "replace")
23
23
24
24
25 def cast_unicode(s, encoding=None):
25 def cast_unicode(s, encoding=None):
26 if isinstance(s, bytes):
26 if isinstance(s, bytes):
27 return decode(s, encoding)
27 return decode(s, encoding)
28 return s
28 return s
29
29
30 def cast_bytes(s, encoding=None):
30 def cast_bytes(s, encoding=None):
31 if not isinstance(s, bytes):
31 if not isinstance(s, bytes):
32 return encode(s, encoding)
32 return encode(s, encoding)
33 return s
33 return s
34
34
35 def _modify_str_or_docstring(str_change_func):
35 def _modify_str_or_docstring(str_change_func):
36 @functools.wraps(str_change_func)
36 @functools.wraps(str_change_func)
37 def wrapper(func_or_str):
37 def wrapper(func_or_str):
38 if isinstance(func_or_str, basestring):
38 if isinstance(func_or_str, basestring):
39 func = None
39 func = None
40 doc = func_or_str
40 doc = func_or_str
41 else:
41 else:
42 func = func_or_str
42 func = func_or_str
43 doc = func.__doc__
43 doc = func.__doc__
44
44
45 doc = str_change_func(doc)
45 doc = str_change_func(doc)
46
46
47 if func:
47 if func:
48 func.__doc__ = doc
48 func.__doc__ = doc
49 return func
49 return func
50 return doc
50 return doc
51 return wrapper
51 return wrapper
52
52
53 if sys.version_info[0] >= 3:
53 if sys.version_info[0] >= 3:
54 PY3 = True
54 PY3 = True
55
55
56 input = input
56 input = input
57 builtin_mod_name = "builtins"
57 builtin_mod_name = "builtins"
58
58
59 str_to_unicode = no_code
59 str_to_unicode = no_code
60 unicode_to_str = no_code
60 unicode_to_str = no_code
61 str_to_bytes = encode
61 str_to_bytes = encode
62 bytes_to_str = decode
62 bytes_to_str = decode
63 cast_bytes_py2 = no_code
63 cast_bytes_py2 = no_code
64
64
65 string_types = (str,)
66
65 def isidentifier(s, dotted=False):
67 def isidentifier(s, dotted=False):
66 if dotted:
68 if dotted:
67 return all(isidentifier(a) for a in s.split("."))
69 return all(isidentifier(a) for a in s.split("."))
68 return s.isidentifier()
70 return s.isidentifier()
69
71
70 open = orig_open
72 open = orig_open
71
73
72 MethodType = types.MethodType
74 MethodType = types.MethodType
73
75
74 def execfile(fname, glob, loc=None):
76 def execfile(fname, glob, loc=None):
75 loc = loc if (loc is not None) else glob
77 loc = loc if (loc is not None) else glob
76 with open(fname, 'rb') as f:
78 with open(fname, 'rb') as f:
77 exec compile(f.read(), fname, 'exec') in glob, loc
79 exec compile(f.read(), fname, 'exec') in glob, loc
78
80
79 # Refactor print statements in doctests.
81 # Refactor print statements in doctests.
80 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
82 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
81 def _print_statement_sub(match):
83 def _print_statement_sub(match):
82 expr = match.groups('expr')
84 expr = match.groups('expr')
83 return "print(%s)" % expr
85 return "print(%s)" % expr
84
86
85 @_modify_str_or_docstring
87 @_modify_str_or_docstring
86 def doctest_refactor_print(doc):
88 def doctest_refactor_print(doc):
87 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
89 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
88 unfortunately doesn't pick up on our doctests.
90 unfortunately doesn't pick up on our doctests.
89
91
90 Can accept a string or a function, so it can be used as a decorator."""
92 Can accept a string or a function, so it can be used as a decorator."""
91 return _print_statement_re.sub(_print_statement_sub, doc)
93 return _print_statement_re.sub(_print_statement_sub, doc)
92
94
93 # Abstract u'abc' syntax:
95 # Abstract u'abc' syntax:
94 @_modify_str_or_docstring
96 @_modify_str_or_docstring
95 def u_format(s):
97 def u_format(s):
96 """"{u}'abc'" --> "'abc'" (Python 3)
98 """"{u}'abc'" --> "'abc'" (Python 3)
97
99
98 Accepts a string or a function, so it can be used as a decorator."""
100 Accepts a string or a function, so it can be used as a decorator."""
99 return s.format(u='')
101 return s.format(u='')
100
102
101 else:
103 else:
102 PY3 = False
104 PY3 = False
103
105
104 input = raw_input
106 input = raw_input
105 builtin_mod_name = "__builtin__"
107 builtin_mod_name = "__builtin__"
106
108
107 str_to_unicode = decode
109 str_to_unicode = decode
108 unicode_to_str = encode
110 unicode_to_str = encode
109 str_to_bytes = no_code
111 str_to_bytes = no_code
110 bytes_to_str = no_code
112 bytes_to_str = no_code
111 cast_bytes_py2 = cast_bytes
113 cast_bytes_py2 = cast_bytes
112
114
115 string_types = (str, unicode)
116
113 import re
117 import re
114 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
118 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
115 def isidentifier(s, dotted=False):
119 def isidentifier(s, dotted=False):
116 if dotted:
120 if dotted:
117 return all(isidentifier(a) for a in s.split("."))
121 return all(isidentifier(a) for a in s.split("."))
118 return bool(_name_re.match(s))
122 return bool(_name_re.match(s))
119
123
120 class open(object):
124 class open(object):
121 """Wrapper providing key part of Python 3 open() interface."""
125 """Wrapper providing key part of Python 3 open() interface."""
122 def __init__(self, fname, mode="r", encoding="utf-8"):
126 def __init__(self, fname, mode="r", encoding="utf-8"):
123 self.f = orig_open(fname, mode)
127 self.f = orig_open(fname, mode)
124 self.enc = encoding
128 self.enc = encoding
125
129
126 def write(self, s):
130 def write(self, s):
127 return self.f.write(s.encode(self.enc))
131 return self.f.write(s.encode(self.enc))
128
132
129 def read(self, size=-1):
133 def read(self, size=-1):
130 return self.f.read(size).decode(self.enc)
134 return self.f.read(size).decode(self.enc)
131
135
132 def close(self):
136 def close(self):
133 return self.f.close()
137 return self.f.close()
134
138
135 def __enter__(self):
139 def __enter__(self):
136 return self
140 return self
137
141
138 def __exit__(self, etype, value, traceback):
142 def __exit__(self, etype, value, traceback):
139 self.f.close()
143 self.f.close()
140
144
141 def MethodType(func, instance):
145 def MethodType(func, instance):
142 return types.MethodType(func, instance, type(instance))
146 return types.MethodType(func, instance, type(instance))
143
147
144 # don't override system execfile on 2.x:
148 # don't override system execfile on 2.x:
145 execfile = execfile
149 execfile = execfile
146
150
147 def doctest_refactor_print(func_or_str):
151 def doctest_refactor_print(func_or_str):
148 return func_or_str
152 return func_or_str
149
153
150
154
151 # Abstract u'abc' syntax:
155 # Abstract u'abc' syntax:
152 @_modify_str_or_docstring
156 @_modify_str_or_docstring
153 def u_format(s):
157 def u_format(s):
154 """"{u}'abc'" --> "u'abc'" (Python 2)
158 """"{u}'abc'" --> "u'abc'" (Python 2)
155
159
156 Accepts a string or a function, so it can be used as a decorator."""
160 Accepts a string or a function, so it can be used as a decorator."""
157 return s.format(u='u')
161 return s.format(u='u')
158
162
159 if sys.platform == 'win32':
163 if sys.platform == 'win32':
160 def execfile(fname, glob=None, loc=None):
164 def execfile(fname, glob=None, loc=None):
161 loc = loc if (loc is not None) else glob
165 loc = loc if (loc is not None) else glob
162 # The rstrip() is necessary b/c trailing whitespace in files will
166 # The rstrip() is necessary b/c trailing whitespace in files will
163 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
167 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
164 # but we still support 2.6). See issue 1027.
168 # but we still support 2.6). See issue 1027.
165 scripttext = __builtin__.open(fname).read().rstrip() + '\n'
169 scripttext = __builtin__.open(fname).read().rstrip() + '\n'
166 # compile converts unicode filename to str assuming
170 # compile converts unicode filename to str assuming
167 # ascii. Let's do the conversion before calling compile
171 # ascii. Let's do the conversion before calling compile
168 if isinstance(fname, unicode):
172 if isinstance(fname, unicode):
169 filename = unicode_to_str(fname)
173 filename = unicode_to_str(fname)
170 else:
174 else:
171 filename = fname
175 filename = fname
172 exec compile(scripttext, filename, 'exec') in glob, loc
176 exec compile(scripttext, filename, 'exec') in glob, loc
173 else:
177 else:
174 def execfile(fname, *where):
178 def execfile(fname, *where):
175 if isinstance(fname, unicode):
179 if isinstance(fname, unicode):
176 filename = fname.encode(sys.getfilesystemencoding())
180 filename = fname.encode(sys.getfilesystemencoding())
177 else:
181 else:
178 filename = fname
182 filename = fname
179 __builtin__.execfile(filename, *where)
183 __builtin__.execfile(filename, *where)
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now