##// END OF EJS Templates
Fixing two minor things for review....
Brian E. Granger -
Show More
@@ -1,373 +1,373 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats.
3 3
4 4 Authors:
5 5
6 6 * Brian Granger
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2008-2010 The IPython Development Team
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 from .displaypub import (
21 21 publish_pretty, publish_html,
22 22 publish_latex, publish_svg,
23 23 publish_png, publish_json,
24 24 publish_javascript, publish_jpeg
25 25 )
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Main functions
29 29 #-----------------------------------------------------------------------------
30 30
31 31 def display(*objs, **kwargs):
32 32 """Display a Python object in all frontends.
33 33
34 34 By default all representations will be computed and sent to the frontends.
35 35 Frontends can decide which representation is used and how.
36 36
37 37 Parameters
38 38 ----------
39 39 objs : tuple of objects
40 40 The Python objects to display.
41 41 include : list or tuple, optional
42 42 A list of format type strings (MIME types) to include in the
43 43 format data dict. If this is set *only* the format types included
44 44 in this list will be computed.
45 45 exclude : list or tuple, optional
46 46 A list of format type string (MIME types) to exclue in the format
47 47 data dict. If this is set all format types will be computed,
48 48 except for those included in this argument.
49 49 """
50 50 include = kwargs.get('include')
51 51 exclude = kwargs.get('exclude')
52 52
53 53 from IPython.core.interactiveshell import InteractiveShell
54 54 inst = InteractiveShell.instance()
55 55 format = inst.display_formatter.format
56 56 publish = inst.display_pub.publish
57 57
58 58 for obj in objs:
59 59 format_dict = format(obj, include=include, exclude=exclude)
60 60 publish('IPython.core.display.display', format_dict)
61 61
62 62
63 63 def display_pretty(*objs, **kwargs):
64 64 """Display the pretty (default) representation of an object.
65 65
66 66 Parameters
67 67 ----------
68 68 objs : tuple of objects
69 69 The Python objects to display, or if raw=True raw text data to
70 70 display.
71 71 raw : bool
72 72 Are the data objects raw data or Python objects that need to be
73 73 formatted before display? [default: False]
74 74 """
75 75 raw = kwargs.pop('raw',False)
76 76 if raw:
77 77 for obj in objs:
78 78 publish_pretty(obj)
79 79 else:
80 80 display(*objs, include=['text/plain'])
81 81
82 82
83 83 def display_html(*objs, **kwargs):
84 84 """Display the HTML representation of an object.
85 85
86 86 Parameters
87 87 ----------
88 88 objs : tuple of objects
89 89 The Python objects to display, or if raw=True raw HTML data to
90 90 display.
91 91 raw : bool
92 92 Are the data objects raw data or Python objects that need to be
93 93 formatted before display? [default: False]
94 94 """
95 95 raw = kwargs.pop('raw',False)
96 96 if raw:
97 97 for obj in objs:
98 98 publish_html(obj)
99 99 else:
100 100 display(*objs, include=['text/plain','text/html'])
101 101
102 102
103 103 def display_svg(*objs, **kwargs):
104 104 """Display the SVG representation of an object.
105 105
106 106 Parameters
107 107 ----------
108 108 objs : tuple of objects
109 109 The Python objects to display, or if raw=True raw svg data to
110 110 display.
111 111 raw : bool
112 112 Are the data objects raw data or Python objects that need to be
113 113 formatted before display? [default: False]
114 114 """
115 115 raw = kwargs.pop('raw',False)
116 116 if raw:
117 117 for obj in objs:
118 118 publish_svg(obj)
119 119 else:
120 120 display(*objs, include=['text/plain','image/svg+xml'])
121 121
122 122
123 123 def display_png(*objs, **kwargs):
124 124 """Display the PNG representation of an object.
125 125
126 126 Parameters
127 127 ----------
128 128 objs : tuple of objects
129 129 The Python objects to display, or if raw=True raw png data to
130 130 display.
131 131 raw : bool
132 132 Are the data objects raw data or Python objects that need to be
133 133 formatted before display? [default: False]
134 134 """
135 135 raw = kwargs.pop('raw',False)
136 136 if raw:
137 137 for obj in objs:
138 138 publish_png(obj)
139 139 else:
140 140 display(*objs, include=['text/plain','image/png'])
141 141
142 142
143 143 def display_jpeg(*objs, **kwargs):
144 144 """Display the JPEG representation of an object.
145 145
146 146 Parameters
147 147 ----------
148 148 objs : tuple of objects
149 149 The Python objects to display, or if raw=True raw JPEG data to
150 150 display.
151 151 raw : bool
152 152 Are the data objects raw data or Python objects that need to be
153 153 formatted before display? [default: False]
154 154 """
155 155 raw = kwargs.pop('raw',False)
156 156 if raw:
157 157 for obj in objs:
158 publish_png(obj)
158 publish_jpeg(obj)
159 159 else:
160 160 display(*objs, include=['text/plain','image/jpeg'])
161 161
162 162
163 163 def display_latex(*objs, **kwargs):
164 164 """Display the LaTeX representation of an object.
165 165
166 166 Parameters
167 167 ----------
168 168 objs : tuple of objects
169 169 The Python objects to display, or if raw=True raw latex data to
170 170 display.
171 171 raw : bool
172 172 Are the data objects raw data or Python objects that need to be
173 173 formatted before display? [default: False]
174 174 """
175 175 raw = kwargs.pop('raw',False)
176 176 if raw:
177 177 for obj in objs:
178 178 publish_latex(obj)
179 179 else:
180 180 display(*objs, include=['text/plain','text/latex'])
181 181
182 182
183 183 def display_json(*objs, **kwargs):
184 184 """Display the JSON representation of an object.
185 185
186 186 Parameters
187 187 ----------
188 188 objs : tuple of objects
189 189 The Python objects to display, or if raw=True raw json data to
190 190 display.
191 191 raw : bool
192 192 Are the data objects raw data or Python objects that need to be
193 193 formatted before display? [default: False]
194 194 """
195 195 raw = kwargs.pop('raw',False)
196 196 if raw:
197 197 for obj in objs:
198 198 publish_json(obj)
199 199 else:
200 200 display(*objs, include=['text/plain','application/json'])
201 201
202 202
203 203 def display_javascript(*objs, **kwargs):
204 204 """Display the Javascript representation of an object.
205 205
206 206 Parameters
207 207 ----------
208 208 objs : tuple of objects
209 209 The Python objects to display, or if raw=True raw javascript data to
210 210 display.
211 211 raw : bool
212 212 Are the data objects raw data or Python objects that need to be
213 213 formatted before display? [default: False]
214 214 """
215 215 raw = kwargs.pop('raw',False)
216 216 if raw:
217 217 for obj in objs:
218 218 publish_javascript(obj)
219 219 else:
220 220 display(*objs, include=['text/plain','application/javascript'])
221 221
222 222 #-----------------------------------------------------------------------------
223 223 # Smart classes
224 224 #-----------------------------------------------------------------------------
225 225
226 226
227 227 class DisplayObject(object):
228 228 """An object that wraps data to be displayed."""
229 229
230 230 _read_flags = 'r'
231 231
232 232 def __init__(self, data=None, url=None, filename=None):
233 233 """Create a display object given raw data.
234 234
235 235 When this object is returned by an expression or passed to the
236 236 display function, it will result in the data being displayed
237 237 in the frontend. The MIME type of the data should match the
238 238 subclasses used, so the Png subclass should be used for 'image/png'
239 239 data. If the data is a URL, the data will first be downloaded
240 240 and then displayed. If
241 241
242 242 Parameters
243 243 ----------
244 244 data : unicode, str or bytes
245 245 The raw data or a URL to download the data from.
246 246 url : unicode
247 247 A URL to download the data from.
248 248 filename : unicode
249 249 Path to a local file to load the data from.
250 250 """
251 251 if data is not None and data.startswith('http'):
252 252 self.url = data
253 253 self.filename = None
254 254 self.data = None
255 255 else:
256 256 self.data = data
257 257 self.url = url
258 258 self.filename = None if filename is None else unicode(filename)
259 259 self.reload()
260 260
261 261 def reload(self):
262 262 """Reload the raw data from file or URL."""
263 263 if self.filename is not None:
264 264 with open(self.filename, self._read_flags) as f:
265 265 self.data = f.read()
266 266 elif self.url is not None:
267 267 try:
268 268 import urllib2
269 269 response = urllib2.urlopen(self.url)
270 270 self.data = response.read()
271 271 except:
272 272 self.data = None
273 273
274 274 class Pretty(DisplayObject):
275 275
276 276 def _repr_pretty_(self):
277 277 return self.data
278 278
279 279
280 280 class HTML(DisplayObject):
281 281
282 282 def _repr_html_(self):
283 283 return self.data
284 284
285 285
286 286 class Math(DisplayObject):
287 287
288 288 def _repr_latex_(self):
289 289 return self.data
290 290
291 291
292 292 class SVG(DisplayObject):
293 293
294 294 def _repr_svg_(self):
295 295 return self.data
296 296
297 297
298 298 class JSON(DisplayObject):
299 299
300 300 def _repr_json_(self):
301 301 return self.data
302 302
303 303
304 304 class Javascript(DisplayObject):
305 305
306 306 def _repr_javascript_(self):
307 307 return self.data
308 308
309 309
310 310 class Image(DisplayObject):
311 311
312 312 _read_flags = 'rb'
313 313
314 314 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=False):
315 315 """Create a display an PNG/JPEG image given raw data.
316 316
317 317 When this object is returned by an expression or passed to the
318 318 display function, it will result in the image being displayed
319 319 in the frontend.
320 320
321 321 Parameters
322 322 ----------
323 323 data : unicode, str or bytes
324 324 The raw data or a URL to download the data from.
325 325 url : unicode
326 326 A URL to download the data from.
327 327 filename : unicode
328 328 Path to a local file to load the data from.
329 329 format : unicode
330 330 The format of the image data (png/jpeg/jpg). If a filename or URL is given
331 331 for format will be inferred from the filename extension.
332 332 embed : bool
333 333 Should the image data be embedded in the notebook using a data URI (True)
334 334 or be loaded using an <img> tag. Set this to True if you want the image
335 335 to be viewable later with no internet connection. If a filename is given
336 336 embed is always set to True.
337 337 """
338 338 if filename is not None:
339 339 ext = self._find_ext(filename)
340 340 elif url is not None:
341 341 ext = self._find_ext(url)
342 342 elif data.startswith('http'):
343 343 ext = self._find_ext(data)
344 344 else:
345 345 ext = None
346 346 if ext is not None:
347 347 if ext == u'jpg' or ext == u'jpeg':
348 348 format = u'jpeg'
349 349 if ext == u'png':
350 350 format = u'png'
351 351 self.format = unicode(format).lower()
352 352 self.embed = True if filename is not None else embed
353 353 super(Image, self).__init__(data=data, url=url, filename=filename)
354 354
355 355 def reload(self):
356 356 """Reload the raw data from file or URL."""
357 357 if self.embed:
358 358 super(Image,self).reload()
359 359
360 360 def _repr_html_(self):
361 361 if not self.embed:
362 362 return u'<img src="%s" />' % self.url
363 363
364 364 def _repr_png_(self):
365 365 if self.embed and self.format == u'png':
366 366 return self.data
367 367
368 368 def _repr_jpeg_(self):
369 369 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
370 370 return self.data
371 371
372 372 def _find_ext(self, s):
373 373 return unicode(s.split('.')[-1].lower())
@@ -1,298 +1,298 b''
1 1 """An interface for publishing rich data to frontends.
2 2
3 3 There are two components of the display system:
4 4
5 5 * Display formatters, which take a Python object and compute the
6 6 representation of the object in various formats (text, HTML, SVg, etc.).
7 7 * The display publisher that is used to send the representation data to the
8 8 various frontends.
9 9
10 10 This module defines the logic display publishing. The display publisher uses
11 11 the ``display_data`` message type that is defined in the IPython messaging
12 12 spec.
13 13
14 14 Authors:
15 15
16 16 * Brian Granger
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008-2010 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Imports
28 28 #-----------------------------------------------------------------------------
29 29
30 30 from __future__ import print_function
31 31
32 32 from IPython.config.configurable import Configurable
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Main payload class
36 36 #-----------------------------------------------------------------------------
37 37
38 38 class DisplayPublisher(Configurable):
39 39 """A traited class that publishes display data to frontends.
40 40
41 41 Instances of this class are created by the main IPython object and should
42 42 be accessed there.
43 43 """
44 44
45 45 def _validate_data(self, source, data, metadata=None):
46 46 """Validate the display data.
47 47
48 48 Parameters
49 49 ----------
50 50 source : str
51 51 The fully dotted name of the callable that created the data, like
52 52 :func:`foo.bar.my_formatter`.
53 53 data : dict
54 54 The formata data dictionary.
55 55 metadata : dict
56 56 Any metadata for the data.
57 57 """
58 58
59 if not isinstance(source, (str,unicode)):
59 if not isinstance(source, basestring):
60 60 raise TypeError('source must be a str, got: %r' % source)
61 61 if not isinstance(data, dict):
62 62 raise TypeError('data must be a dict, got: %r' % data)
63 63 if metadata is not None:
64 64 if not isinstance(metadata, dict):
65 65 raise TypeError('metadata must be a dict, got: %r' % data)
66 66
67 67 def publish(self, source, data, metadata=None):
68 68 """Publish data and metadata to all frontends.
69 69
70 70 See the ``display_data`` message in the messaging documentation for
71 71 more details about this message type.
72 72
73 73 The following MIME types are currently implemented:
74 74
75 75 * text/plain
76 76 * text/html
77 77 * text/latex
78 78 * application/json
79 79 * application/javascript
80 80 * image/png
81 81 * image/jpeg
82 82 * image/svg+xml
83 83
84 84 Parameters
85 85 ----------
86 86 source : str
87 87 A string that give the function or method that created the data,
88 88 such as 'IPython.core.page'.
89 89 data : dict
90 90 A dictionary having keys that are valid MIME types (like
91 91 'text/plain' or 'image/svg+xml') and values that are the data for
92 92 that MIME type. The data itself must be a JSON'able data
93 93 structure. Minimally all data should have the 'text/plain' data,
94 94 which can be displayed by all frontends. If more than the plain
95 95 text is given, it is up to the frontend to decide which
96 96 representation to use.
97 97 metadata : dict
98 98 A dictionary for metadata related to the data. This can contain
99 99 arbitrary key, value pairs that frontends can use to interpret
100 100 the data.
101 101 """
102 102 from IPython.utils import io
103 103 # The default is to simply write the plain text data using io.stdout.
104 104 if data.has_key('text/plain'):
105 105 print(data['text/plain'], file=io.stdout)
106 106
107 107
108 108 def publish_display_data(source, data, metadata=None):
109 109 """Publish data and metadata to all frontends.
110 110
111 111 See the ``display_data`` message in the messaging documentation for
112 112 more details about this message type.
113 113
114 114 The following MIME types are currently implemented:
115 115
116 116 * text/plain
117 117 * text/html
118 118 * text/latex
119 119 * application/json
120 120 * application/javascript
121 121 * image/png
122 122 * image/jpeg
123 123 * image/svg+xml
124 124
125 125 Parameters
126 126 ----------
127 127 source : str
128 128 A string that give the function or method that created the data,
129 129 such as 'IPython.core.page'.
130 130 data : dict
131 131 A dictionary having keys that are valid MIME types (like
132 132 'text/plain' or 'image/svg+xml') and values that are the data for
133 133 that MIME type. The data itself must be a JSON'able data
134 134 structure. Minimally all data should have the 'text/plain' data,
135 135 which can be displayed by all frontends. If more than the plain
136 136 text is given, it is up to the frontend to decide which
137 137 representation to use.
138 138 metadata : dict
139 139 A dictionary for metadata related to the data. This can contain
140 140 arbitrary key, value pairs that frontends can use to interpret
141 141 the data.
142 142 """
143 143 from IPython.core.interactiveshell import InteractiveShell
144 144 InteractiveShell.instance().display_pub.publish(
145 145 source,
146 146 data,
147 147 metadata
148 148 )
149 149
150 150
151 151 def publish_pretty(data, metadata=None):
152 152 """Publish raw text data to all frontends.
153 153
154 154 Parameters
155 155 ----------
156 156 data : unicode
157 157 The raw text data to publish.
158 158 metadata : dict
159 159 A dictionary for metadata related to the data. This can contain
160 160 arbitrary key, value pairs that frontends can use to interpret
161 161 the data.
162 162 """
163 163 publish_display_data(
164 164 u'IPython.core.displaypub.publish_pretty',
165 165 {'text/plain':data},
166 166 metadata=metadata
167 167 )
168 168
169 169
170 170 def publish_html(data, metadata=None):
171 171 """Publish raw HTML data to all frontends.
172 172
173 173 Parameters
174 174 ----------
175 175 data : unicode
176 176 The raw HTML data to publish.
177 177 metadata : dict
178 178 A dictionary for metadata related to the data. This can contain
179 179 arbitrary key, value pairs that frontends can use to interpret
180 180 the data.
181 181 """
182 182 publish_display_data(
183 183 u'IPython.core.displaypub.publish_html',
184 184 {'text/html':data},
185 185 metadata=metadata
186 186 )
187 187
188 188
189 189 def publish_latex(data, metadata=None):
190 190 """Publish raw LaTeX data to all frontends.
191 191
192 192 Parameters
193 193 ----------
194 194 data : unicode
195 195 The raw LaTeX data to publish.
196 196 metadata : dict
197 197 A dictionary for metadata related to the data. This can contain
198 198 arbitrary key, value pairs that frontends can use to interpret
199 199 the data.
200 200 """
201 201 publish_display_data(
202 202 u'IPython.core.displaypub.publish_latex',
203 203 {'text/latex':data},
204 204 metadata=metadata
205 205 )
206 206
207 207 def publish_png(data, metadata=None):
208 208 """Publish raw binary PNG data to all frontends.
209 209
210 210 Parameters
211 211 ----------
212 212 data : str/bytes
213 213 The raw binary PNG data to publish.
214 214 metadata : dict
215 215 A dictionary for metadata related to the data. This can contain
216 216 arbitrary key, value pairs that frontends can use to interpret
217 217 the data.
218 218 """
219 219 publish_display_data(
220 220 u'IPython.core.displaypub.publish_png',
221 221 {'image/png':data},
222 222 metadata=metadata
223 223 )
224 224
225 225
226 226 def publish_jpeg(data, metadata=None):
227 227 """Publish raw binary JPEG data to all frontends.
228 228
229 229 Parameters
230 230 ----------
231 231 data : str/bytes
232 232 The raw binary JPEG data to publish.
233 233 metadata : dict
234 234 A dictionary for metadata related to the data. This can contain
235 235 arbitrary key, value pairs that frontends can use to interpret
236 236 the data.
237 237 """
238 238 publish_display_data(
239 239 u'IPython.core.displaypub.publish_jpeg',
240 240 {'image/jpeg':data},
241 241 metadata=metadata
242 242 )
243 243
244 244
245 245 def publish_svg(data, metadata=None):
246 246 """Publish raw SVG data to all frontends.
247 247
248 248 Parameters
249 249 ----------
250 250 data : unicode
251 251 The raw SVG data to publish.
252 252 metadata : dict
253 253 A dictionary for metadata related to the data. This can contain
254 254 arbitrary key, value pairs that frontends can use to interpret
255 255 the data.
256 256 """
257 257 publish_display_data(
258 258 u'IPython.core.displaypub.publish_svg',
259 259 {'image/svg+xml':data},
260 260 metadata=metadata
261 261 )
262 262
263 263 def publish_json(data, metadata=None):
264 264 """Publish raw JSON data to all frontends.
265 265
266 266 Parameters
267 267 ----------
268 268 data : unicode
269 269 The raw JSON data to publish.
270 270 metadata : dict
271 271 A dictionary for metadata related to the data. This can contain
272 272 arbitrary key, value pairs that frontends can use to interpret
273 273 the data.
274 274 """
275 275 publish_display_data(
276 276 u'IPython.core.displaypub.publish_json',
277 277 {'application/json':data},
278 278 metadata=metadata
279 279 )
280 280
281 281 def publish_javascript(data, metadata=None):
282 282 """Publish raw Javascript data to all frontends.
283 283
284 284 Parameters
285 285 ----------
286 286 data : unicode
287 287 The raw Javascript data to publish.
288 288 metadata : dict
289 289 A dictionary for metadata related to the data. This can contain
290 290 arbitrary key, value pairs that frontends can use to interpret
291 291 the data.
292 292 """
293 293 publish_display_data(
294 294 u'IPython.core.displaypub.publish_javascript',
295 295 {'application/javascript':data},
296 296 metadata=metadata
297 297 )
298 298
General Comments 0
You need to be logged in to leave comments. Login now