Show More
@@ -1,815 +1,816 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Display formatters. |
|
3 | 3 | |
|
4 | 4 | Inheritance diagram: |
|
5 | 5 | |
|
6 | 6 | .. inheritance-diagram:: IPython.core.formatters |
|
7 | 7 | :parts: 3 |
|
8 | 8 | |
|
9 | 9 | Authors: |
|
10 | 10 | |
|
11 | 11 | * Robert Kern |
|
12 | 12 | * Brian Granger |
|
13 | 13 | """ |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Copyright (C) 2010-2011, IPython Development Team. |
|
16 | 16 | # |
|
17 | 17 | # Distributed under the terms of the Modified BSD License. |
|
18 | 18 | # |
|
19 | 19 | # The full license is in the file COPYING.txt, distributed with this software. |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | # Stdlib imports |
|
27 | 27 | import abc |
|
28 | 28 | import sys |
|
29 | 29 | import warnings |
|
30 | 30 | |
|
31 | 31 | from IPython.external.decorator import decorator |
|
32 | 32 | |
|
33 | 33 | # Our own imports |
|
34 | 34 | from IPython.config.configurable import Configurable |
|
35 | 35 | from IPython.lib import pretty |
|
36 | 36 | from IPython.utils import io |
|
37 | 37 | from IPython.utils.traitlets import ( |
|
38 | 38 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
39 | 39 | ) |
|
40 | 40 | from IPython.utils.warn import warn |
|
41 | 41 | from IPython.utils.py3compat import ( |
|
42 | 42 | unicode_to_str, with_metaclass, PY3, string_types, |
|
43 | 43 | ) |
|
44 | 44 | |
|
45 | 45 | if PY3: |
|
46 | 46 | from io import StringIO |
|
47 | 47 | else: |
|
48 | 48 | from StringIO import StringIO |
|
49 | 49 | |
|
50 | 50 | |
|
51 | 51 | #----------------------------------------------------------------------------- |
|
52 | 52 | # The main DisplayFormatter class |
|
53 | 53 | #----------------------------------------------------------------------------- |
|
54 | 54 | |
|
55 | 55 | class DisplayFormatter(Configurable): |
|
56 | 56 | |
|
57 | 57 | # When set to true only the default plain text formatter will be used. |
|
58 | 58 | plain_text_only = Bool(False, config=True) |
|
59 | 59 | def _plain_text_only_changed(self, name, old, new): |
|
60 | 60 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
61 | 61 | |
|
62 | 62 | Use DisplayFormatter.active_types = ['text/plain'] |
|
63 | 63 | for the same effect. |
|
64 | 64 | """, DeprecationWarning) |
|
65 | 65 | if new: |
|
66 | 66 | self.active_types = ['text/plain'] |
|
67 | 67 | else: |
|
68 | 68 | self.active_types = self.format_types |
|
69 | 69 | |
|
70 | 70 | active_types = List(Unicode, config=True, |
|
71 | 71 | help="""List of currently active mime-types to display. |
|
72 | 72 | You can use this to set a white-list for formats to display. |
|
73 | 73 | |
|
74 | 74 | Most users will not need to change this value. |
|
75 | 75 | """) |
|
76 | 76 | def _active_types_default(self): |
|
77 | 77 | return self.format_types |
|
78 | 78 | |
|
79 | 79 | def _active_types_changed(self, name, old, new): |
|
80 | 80 | for key, formatter in self.formatters.items(): |
|
81 | 81 | if key in new: |
|
82 | 82 | formatter.enabled = True |
|
83 | 83 | else: |
|
84 | 84 | formatter.enabled = False |
|
85 | 85 | |
|
86 | 86 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
87 | 87 | # values are subclasses of BaseFormatter. |
|
88 | 88 | formatters = Dict() |
|
89 | 89 | def _formatters_default(self): |
|
90 | 90 | """Activate the default formatters.""" |
|
91 | 91 | formatter_classes = [ |
|
92 | 92 | PlainTextFormatter, |
|
93 | 93 | HTMLFormatter, |
|
94 | 94 | SVGFormatter, |
|
95 | 95 | PNGFormatter, |
|
96 | 96 | JPEGFormatter, |
|
97 | 97 | LatexFormatter, |
|
98 | 98 | JSONFormatter, |
|
99 | 99 | JavascriptFormatter |
|
100 | 100 | ] |
|
101 | 101 | d = {} |
|
102 | 102 | for cls in formatter_classes: |
|
103 | 103 | f = cls(parent=self) |
|
104 | 104 | d[f.format_type] = f |
|
105 | 105 | return d |
|
106 | 106 | |
|
107 | 107 | def format(self, obj, include=None, exclude=None): |
|
108 | 108 | """Return a format data dict for an object. |
|
109 | 109 | |
|
110 | 110 | By default all format types will be computed. |
|
111 | 111 | |
|
112 | 112 | The following MIME types are currently implemented: |
|
113 | 113 | |
|
114 | 114 | * text/plain |
|
115 | 115 | * text/html |
|
116 | 116 | * text/latex |
|
117 | 117 | * application/json |
|
118 | 118 | * application/javascript |
|
119 | 119 | * image/png |
|
120 | 120 | * image/jpeg |
|
121 | 121 | * image/svg+xml |
|
122 | 122 | |
|
123 | 123 | Parameters |
|
124 | 124 | ---------- |
|
125 | 125 | obj : object |
|
126 | 126 | The Python object whose format data will be computed. |
|
127 | 127 | include : list or tuple, optional |
|
128 | 128 | A list of format type strings (MIME types) to include in the |
|
129 | 129 | format data dict. If this is set *only* the format types included |
|
130 | 130 | in this list will be computed. |
|
131 | 131 | exclude : list or tuple, optional |
|
132 | 132 | A list of format type string (MIME types) to exclude in the format |
|
133 | 133 | data dict. If this is set all format types will be computed, |
|
134 | 134 | except for those included in this argument. |
|
135 | 135 | |
|
136 | 136 | Returns |
|
137 | 137 | ------- |
|
138 | 138 | (format_dict, metadata_dict) : tuple of two dicts |
|
139 | 139 | |
|
140 | 140 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
141 | 141 | generated for the object. The keys are the format types, which |
|
142 | 142 | will usually be MIME type strings and the values and JSON'able |
|
143 | 143 | data structure containing the raw data for the representation in |
|
144 | 144 | that format. |
|
145 | 145 | |
|
146 | 146 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
147 | 147 | Its keys will be a strict subset of the keys in format_dict. |
|
148 | 148 | """ |
|
149 | 149 | format_dict = {} |
|
150 | 150 | md_dict = {} |
|
151 | 151 | |
|
152 | 152 | for format_type, formatter in self.formatters.items(): |
|
153 | 153 | if include and format_type not in include: |
|
154 | 154 | continue |
|
155 | 155 | if exclude and format_type in exclude: |
|
156 | 156 | continue |
|
157 | 157 | |
|
158 | 158 | md = None |
|
159 | 159 | try: |
|
160 | 160 | data = formatter(obj) |
|
161 | 161 | except: |
|
162 | 162 | # FIXME: log the exception |
|
163 | 163 | raise |
|
164 | 164 | |
|
165 | 165 | # formatters can return raw data or (data, metadata) |
|
166 | 166 | if isinstance(data, tuple) and len(data) == 2: |
|
167 | 167 | data, md = data |
|
168 | 168 | |
|
169 | 169 | if data is not None: |
|
170 | 170 | format_dict[format_type] = data |
|
171 | 171 | if md is not None: |
|
172 | 172 | md_dict[format_type] = md |
|
173 | 173 | |
|
174 | 174 | return format_dict, md_dict |
|
175 | 175 | |
|
176 | 176 | @property |
|
177 | 177 | def format_types(self): |
|
178 | 178 | """Return the format types (MIME types) of the active formatters.""" |
|
179 | 179 | return list(self.formatters.keys()) |
|
180 | 180 | |
|
181 | 181 | |
|
182 | 182 | #----------------------------------------------------------------------------- |
|
183 | 183 | # Formatters for specific format types (text, html, svg, etc.) |
|
184 | 184 | #----------------------------------------------------------------------------- |
|
185 | 185 | |
|
186 | 186 | @decorator |
|
187 | 187 | def warn_format_error(method, self, *args, **kwargs): |
|
188 | 188 | """decorator for warning on failed format call""" |
|
189 | 189 | try: |
|
190 | 190 | r = method(self, *args, **kwargs) |
|
191 | 191 | except Exception as e: |
|
192 | 192 | warn("Exception in %s formatter: %s" % (self.format_type, e)) |
|
193 | 193 | return None |
|
194 |
if r is None or isinstance(r, self._return_type) |
|
|
194 | if r is None or isinstance(r, self._return_type) or \ | |
|
195 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): | |
|
195 | 196 | return r |
|
196 | 197 | else: |
|
197 | 198 | warn("%s formatter returned invalid type %s for object: %s" % ( |
|
198 |
self.format_type, type(r), pretty._safe_repr( |
|
|
199 | self.format_type, type(r), pretty._safe_repr(args[0]) | |
|
199 | 200 | )) |
|
200 | 201 | |
|
201 | 202 | |
|
202 | 203 | |
|
203 | 204 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
204 | 205 | """ Abstract base class for Formatters. |
|
205 | 206 | |
|
206 | 207 | A formatter is a callable class that is responsible for computing the |
|
207 | 208 | raw format data for a particular format type (MIME type). For example, |
|
208 | 209 | an HTML formatter would have a format type of `text/html` and would return |
|
209 | 210 | the HTML representation of the object when called. |
|
210 | 211 | """ |
|
211 | 212 | |
|
212 | 213 | # The format type of the data returned, usually a MIME type. |
|
213 | 214 | format_type = 'text/plain' |
|
214 | 215 | |
|
215 | 216 | # Is the formatter enabled... |
|
216 | 217 | enabled = True |
|
217 | 218 | |
|
218 | 219 | @abc.abstractmethod |
|
219 | 220 | @warn_format_error |
|
220 | 221 | def __call__(self, obj): |
|
221 | 222 | """Return a JSON'able representation of the object. |
|
222 | 223 | |
|
223 | 224 | If the object cannot be formatted by this formatter, |
|
224 | 225 | warn and return None. |
|
225 | 226 | """ |
|
226 | 227 | return repr(obj) |
|
227 | 228 | |
|
228 | 229 | |
|
229 | 230 | def _mod_name_key(typ): |
|
230 | 231 | """Return a (__module__, __name__) tuple for a type. |
|
231 | 232 | |
|
232 | 233 | Used as key in Formatter.deferred_printers. |
|
233 | 234 | """ |
|
234 | 235 | module = getattr(typ, '__module__', None) |
|
235 | 236 | name = getattr(typ, '__name__', None) |
|
236 | 237 | return (module, name) |
|
237 | 238 | |
|
238 | 239 | |
|
239 | 240 | def _get_type(obj): |
|
240 | 241 | """Return the type of an instance (old and new-style)""" |
|
241 | 242 | return getattr(obj, '__class__', None) or type(obj) |
|
242 | 243 | |
|
243 | 244 | _raise_key_error = object() |
|
244 | 245 | |
|
245 | 246 | |
|
246 | 247 | class BaseFormatter(Configurable): |
|
247 | 248 | """A base formatter class that is configurable. |
|
248 | 249 | |
|
249 | 250 | This formatter should usually be used as the base class of all formatters. |
|
250 | 251 | It is a traited :class:`Configurable` class and includes an extensible |
|
251 | 252 | API for users to determine how their objects are formatted. The following |
|
252 | 253 | logic is used to find a function to format an given object. |
|
253 | 254 | |
|
254 | 255 | 1. The object is introspected to see if it has a method with the name |
|
255 | 256 | :attr:`print_method`. If is does, that object is passed to that method |
|
256 | 257 | for formatting. |
|
257 | 258 | 2. If no print method is found, three internal dictionaries are consulted |
|
258 | 259 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
259 | 260 | and :attr:`deferred_printers`. |
|
260 | 261 | |
|
261 | 262 | Users should use these dictionaries to register functions that will be |
|
262 | 263 | used to compute the format data for their objects (if those objects don't |
|
263 | 264 | have the special print methods). The easiest way of using these |
|
264 | 265 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
265 | 266 | methods. |
|
266 | 267 | |
|
267 | 268 | If no function/callable is found to compute the format data, ``None`` is |
|
268 | 269 | returned and this format type is not used. |
|
269 | 270 | """ |
|
270 | 271 | |
|
271 | 272 | format_type = Unicode('text/plain') |
|
272 | 273 | _return_type = string_types |
|
273 | 274 | |
|
274 | 275 | enabled = Bool(True, config=True) |
|
275 | 276 | |
|
276 | 277 | print_method = ObjectName('__repr__') |
|
277 | 278 | |
|
278 | 279 | # The singleton printers. |
|
279 | 280 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
280 | 281 | singleton_printers = Dict(config=True) |
|
281 | 282 | |
|
282 | 283 | # The type-specific printers. |
|
283 | 284 | # Map type objects to the format functions. |
|
284 | 285 | type_printers = Dict(config=True) |
|
285 | 286 | |
|
286 | 287 | # The deferred-import type-specific printers. |
|
287 | 288 | # Map (modulename, classname) pairs to the format functions. |
|
288 | 289 | deferred_printers = Dict(config=True) |
|
289 | 290 | |
|
290 | 291 | @warn_format_error |
|
291 | 292 | def __call__(self, obj): |
|
292 | 293 | """Compute the format for an object.""" |
|
293 | 294 | if self.enabled: |
|
294 | 295 | # lookup registered printer |
|
295 | 296 | try: |
|
296 | 297 | printer = self.lookup(obj) |
|
297 | 298 | except KeyError: |
|
298 | 299 | pass |
|
299 | 300 | else: |
|
300 | 301 | return printer(obj) |
|
301 | 302 | # Finally look for special method names |
|
302 | 303 | method = pretty._safe_getattr(obj, self.print_method, None) |
|
303 | 304 | if method is not None: |
|
304 | 305 | return method() |
|
305 | 306 | return None |
|
306 | 307 | else: |
|
307 | 308 | return None |
|
308 | 309 | |
|
309 | 310 | def __contains__(self, typ): |
|
310 | 311 | """map in to lookup_by_type""" |
|
311 | 312 | try: |
|
312 | 313 | self.lookup_by_type(typ) |
|
313 | 314 | except KeyError: |
|
314 | 315 | return False |
|
315 | 316 | else: |
|
316 | 317 | return True |
|
317 | 318 | |
|
318 | 319 | def lookup(self, obj): |
|
319 | 320 | """Look up the formatter for a given instance. |
|
320 | 321 | |
|
321 | 322 | Parameters |
|
322 | 323 | ---------- |
|
323 | 324 | obj : object instance |
|
324 | 325 | |
|
325 | 326 | Returns |
|
326 | 327 | ------- |
|
327 | 328 | f : callable |
|
328 | 329 | The registered formatting callable for the type. |
|
329 | 330 | |
|
330 | 331 | Raises |
|
331 | 332 | ------ |
|
332 | 333 | KeyError if the type has not been registered. |
|
333 | 334 | """ |
|
334 | 335 | # look for singleton first |
|
335 | 336 | obj_id = id(obj) |
|
336 | 337 | if obj_id in self.singleton_printers: |
|
337 | 338 | return self.singleton_printers[obj_id] |
|
338 | 339 | # then lookup by type |
|
339 | 340 | return self.lookup_by_type(_get_type(obj)) |
|
340 | 341 | |
|
341 | 342 | def lookup_by_type(self, typ): |
|
342 | 343 | """Look up the registered formatter for a type. |
|
343 | 344 | |
|
344 | 345 | Parameters |
|
345 | 346 | ---------- |
|
346 | 347 | typ : type or '__module__.__name__' string for a type |
|
347 | 348 | |
|
348 | 349 | Returns |
|
349 | 350 | ------- |
|
350 | 351 | f : callable |
|
351 | 352 | The registered formatting callable for the type. |
|
352 | 353 | |
|
353 | 354 | Raises |
|
354 | 355 | ------ |
|
355 | 356 | KeyError if the type has not been registered. |
|
356 | 357 | """ |
|
357 | 358 | if isinstance(typ, string_types): |
|
358 | 359 | typ_key = tuple(typ.rsplit('.',1)) |
|
359 | 360 | if typ_key not in self.deferred_printers: |
|
360 | 361 | # We may have it cached in the type map. We will have to |
|
361 | 362 | # iterate over all of the types to check. |
|
362 | 363 | for cls in self.type_printers: |
|
363 | 364 | if _mod_name_key(cls) == typ_key: |
|
364 | 365 | return self.type_printers[cls] |
|
365 | 366 | else: |
|
366 | 367 | return self.deferred_printers[typ_key] |
|
367 | 368 | else: |
|
368 | 369 | for cls in pretty._get_mro(typ): |
|
369 | 370 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
370 | 371 | return self.type_printers[cls] |
|
371 | 372 | |
|
372 | 373 | # If we have reached here, the lookup failed. |
|
373 | 374 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
374 | 375 | |
|
375 | 376 | def for_type(self, typ, func=None): |
|
376 | 377 | """Add a format function for a given type. |
|
377 | 378 | |
|
378 | 379 | Parameters |
|
379 | 380 | ----------- |
|
380 | 381 | typ : type or '__module__.__name__' string for a type |
|
381 | 382 | The class of the object that will be formatted using `func`. |
|
382 | 383 | func : callable |
|
383 | 384 | A callable for computing the format data. |
|
384 | 385 | `func` will be called with the object to be formatted, |
|
385 | 386 | and will return the raw data in this formatter's format. |
|
386 | 387 | Subclasses may use a different call signature for the |
|
387 | 388 | `func` argument. |
|
388 | 389 | |
|
389 | 390 | If `func` is None or not specified, there will be no change, |
|
390 | 391 | only returning the current value. |
|
391 | 392 | |
|
392 | 393 | Returns |
|
393 | 394 | ------- |
|
394 | 395 | oldfunc : callable |
|
395 | 396 | The currently registered callable. |
|
396 | 397 | If you are registering a new formatter, |
|
397 | 398 | this will be the previous value (to enable restoring later). |
|
398 | 399 | """ |
|
399 | 400 | # if string given, interpret as 'pkg.module.class_name' |
|
400 | 401 | if isinstance(typ, string_types): |
|
401 | 402 | type_module, type_name = typ.rsplit('.', 1) |
|
402 | 403 | return self.for_type_by_name(type_module, type_name, func) |
|
403 | 404 | |
|
404 | 405 | try: |
|
405 | 406 | oldfunc = self.lookup_by_type(typ) |
|
406 | 407 | except KeyError: |
|
407 | 408 | oldfunc = None |
|
408 | 409 | |
|
409 | 410 | if func is not None: |
|
410 | 411 | self.type_printers[typ] = func |
|
411 | 412 | |
|
412 | 413 | return oldfunc |
|
413 | 414 | |
|
414 | 415 | def for_type_by_name(self, type_module, type_name, func=None): |
|
415 | 416 | """Add a format function for a type specified by the full dotted |
|
416 | 417 | module and name of the type, rather than the type of the object. |
|
417 | 418 | |
|
418 | 419 | Parameters |
|
419 | 420 | ---------- |
|
420 | 421 | type_module : str |
|
421 | 422 | The full dotted name of the module the type is defined in, like |
|
422 | 423 | ``numpy``. |
|
423 | 424 | type_name : str |
|
424 | 425 | The name of the type (the class name), like ``dtype`` |
|
425 | 426 | func : callable |
|
426 | 427 | A callable for computing the format data. |
|
427 | 428 | `func` will be called with the object to be formatted, |
|
428 | 429 | and will return the raw data in this formatter's format. |
|
429 | 430 | Subclasses may use a different call signature for the |
|
430 | 431 | `func` argument. |
|
431 | 432 | |
|
432 | 433 | If `func` is None or unspecified, there will be no change, |
|
433 | 434 | only returning the current value. |
|
434 | 435 | |
|
435 | 436 | Returns |
|
436 | 437 | ------- |
|
437 | 438 | oldfunc : callable |
|
438 | 439 | The currently registered callable. |
|
439 | 440 | If you are registering a new formatter, |
|
440 | 441 | this will be the previous value (to enable restoring later). |
|
441 | 442 | """ |
|
442 | 443 | key = (type_module, type_name) |
|
443 | 444 | |
|
444 | 445 | try: |
|
445 | 446 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
446 | 447 | except KeyError: |
|
447 | 448 | oldfunc = None |
|
448 | 449 | |
|
449 | 450 | if func is not None: |
|
450 | 451 | self.deferred_printers[key] = func |
|
451 | 452 | return oldfunc |
|
452 | 453 | |
|
453 | 454 | def pop(self, typ, default=_raise_key_error): |
|
454 | 455 | """Pop a formatter for the given type. |
|
455 | 456 | |
|
456 | 457 | Parameters |
|
457 | 458 | ---------- |
|
458 | 459 | typ : type or '__module__.__name__' string for a type |
|
459 | 460 | default : object |
|
460 | 461 | value to be returned if no formatter is registered for typ. |
|
461 | 462 | |
|
462 | 463 | Returns |
|
463 | 464 | ------- |
|
464 | 465 | obj : object |
|
465 | 466 | The last registered object for the type. |
|
466 | 467 | |
|
467 | 468 | Raises |
|
468 | 469 | ------ |
|
469 | 470 | KeyError if the type is not registered and default is not specified. |
|
470 | 471 | """ |
|
471 | 472 | |
|
472 | 473 | if isinstance(typ, string_types): |
|
473 | 474 | typ_key = tuple(typ.rsplit('.',1)) |
|
474 | 475 | if typ_key not in self.deferred_printers: |
|
475 | 476 | # We may have it cached in the type map. We will have to |
|
476 | 477 | # iterate over all of the types to check. |
|
477 | 478 | for cls in self.type_printers: |
|
478 | 479 | if _mod_name_key(cls) == typ_key: |
|
479 | 480 | old = self.type_printers.pop(cls) |
|
480 | 481 | break |
|
481 | 482 | else: |
|
482 | 483 | old = default |
|
483 | 484 | else: |
|
484 | 485 | old = self.deferred_printers.pop(typ_key) |
|
485 | 486 | else: |
|
486 | 487 | if typ in self.type_printers: |
|
487 | 488 | old = self.type_printers.pop(typ) |
|
488 | 489 | else: |
|
489 | 490 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
490 | 491 | if old is _raise_key_error: |
|
491 | 492 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
492 | 493 | return old |
|
493 | 494 | |
|
494 | 495 | def _in_deferred_types(self, cls): |
|
495 | 496 | """ |
|
496 | 497 | Check if the given class is specified in the deferred type registry. |
|
497 | 498 | |
|
498 | 499 | Successful matches will be moved to the regular type registry for future use. |
|
499 | 500 | """ |
|
500 | 501 | mod = getattr(cls, '__module__', None) |
|
501 | 502 | name = getattr(cls, '__name__', None) |
|
502 | 503 | key = (mod, name) |
|
503 | 504 | if key in self.deferred_printers: |
|
504 | 505 | # Move the printer over to the regular registry. |
|
505 | 506 | printer = self.deferred_printers.pop(key) |
|
506 | 507 | self.type_printers[cls] = printer |
|
507 | 508 | return True |
|
508 | 509 | return False |
|
509 | 510 | |
|
510 | 511 | |
|
511 | 512 | class PlainTextFormatter(BaseFormatter): |
|
512 | 513 | """The default pretty-printer. |
|
513 | 514 | |
|
514 | 515 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
515 | 516 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
516 | 517 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
517 | 518 | how to write pretty printers. Here is a simple example:: |
|
518 | 519 | |
|
519 | 520 | def dtype_pprinter(obj, p, cycle): |
|
520 | 521 | if cycle: |
|
521 | 522 | return p.text('dtype(...)') |
|
522 | 523 | if hasattr(obj, 'fields'): |
|
523 | 524 | if obj.fields is None: |
|
524 | 525 | p.text(repr(obj)) |
|
525 | 526 | else: |
|
526 | 527 | p.begin_group(7, 'dtype([') |
|
527 | 528 | for i, field in enumerate(obj.descr): |
|
528 | 529 | if i > 0: |
|
529 | 530 | p.text(',') |
|
530 | 531 | p.breakable() |
|
531 | 532 | p.pretty(field) |
|
532 | 533 | p.end_group(7, '])') |
|
533 | 534 | """ |
|
534 | 535 | |
|
535 | 536 | # The format type of data returned. |
|
536 | 537 | format_type = Unicode('text/plain') |
|
537 | 538 | |
|
538 | 539 | # This subclass ignores this attribute as it always need to return |
|
539 | 540 | # something. |
|
540 | 541 | enabled = Bool(True, config=False) |
|
541 | 542 | |
|
542 | 543 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
543 | 544 | print_method = ObjectName('_repr_pretty_') |
|
544 | 545 | |
|
545 | 546 | # Whether to pretty-print or not. |
|
546 | 547 | pprint = Bool(True, config=True) |
|
547 | 548 | |
|
548 | 549 | # Whether to be verbose or not. |
|
549 | 550 | verbose = Bool(False, config=True) |
|
550 | 551 | |
|
551 | 552 | # The maximum width. |
|
552 | 553 | max_width = Integer(79, config=True) |
|
553 | 554 | |
|
554 | 555 | # The newline character. |
|
555 | 556 | newline = Unicode('\n', config=True) |
|
556 | 557 | |
|
557 | 558 | # format-string for pprinting floats |
|
558 | 559 | float_format = Unicode('%r') |
|
559 | 560 | # setter for float precision, either int or direct format-string |
|
560 | 561 | float_precision = CUnicode('', config=True) |
|
561 | 562 | |
|
562 | 563 | def _float_precision_changed(self, name, old, new): |
|
563 | 564 | """float_precision changed, set float_format accordingly. |
|
564 | 565 | |
|
565 | 566 | float_precision can be set by int or str. |
|
566 | 567 | This will set float_format, after interpreting input. |
|
567 | 568 | If numpy has been imported, numpy print precision will also be set. |
|
568 | 569 | |
|
569 | 570 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
570 | 571 | |
|
571 | 572 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
572 | 573 | |
|
573 | 574 | This parameter can be set via the '%precision' magic. |
|
574 | 575 | """ |
|
575 | 576 | |
|
576 | 577 | if '%' in new: |
|
577 | 578 | # got explicit format string |
|
578 | 579 | fmt = new |
|
579 | 580 | try: |
|
580 | 581 | fmt%3.14159 |
|
581 | 582 | except Exception: |
|
582 | 583 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
583 | 584 | elif new: |
|
584 | 585 | # otherwise, should be an int |
|
585 | 586 | try: |
|
586 | 587 | i = int(new) |
|
587 | 588 | assert i >= 0 |
|
588 | 589 | except ValueError: |
|
589 | 590 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
590 | 591 | except AssertionError: |
|
591 | 592 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
592 | 593 | |
|
593 | 594 | fmt = '%%.%if'%i |
|
594 | 595 | if 'numpy' in sys.modules: |
|
595 | 596 | # set numpy precision if it has been imported |
|
596 | 597 | import numpy |
|
597 | 598 | numpy.set_printoptions(precision=i) |
|
598 | 599 | else: |
|
599 | 600 | # default back to repr |
|
600 | 601 | fmt = '%r' |
|
601 | 602 | if 'numpy' in sys.modules: |
|
602 | 603 | import numpy |
|
603 | 604 | # numpy default is 8 |
|
604 | 605 | numpy.set_printoptions(precision=8) |
|
605 | 606 | self.float_format = fmt |
|
606 | 607 | |
|
607 | 608 | # Use the default pretty printers from IPython.lib.pretty. |
|
608 | 609 | def _singleton_printers_default(self): |
|
609 | 610 | return pretty._singleton_pprinters.copy() |
|
610 | 611 | |
|
611 | 612 | def _type_printers_default(self): |
|
612 | 613 | d = pretty._type_pprinters.copy() |
|
613 | 614 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
614 | 615 | return d |
|
615 | 616 | |
|
616 | 617 | def _deferred_printers_default(self): |
|
617 | 618 | return pretty._deferred_type_pprinters.copy() |
|
618 | 619 | |
|
619 | 620 | #### FormatterABC interface #### |
|
620 | 621 | |
|
621 | 622 | @warn_format_error |
|
622 | 623 | def __call__(self, obj): |
|
623 | 624 | """Compute the pretty representation of the object.""" |
|
624 | 625 | if not self.pprint: |
|
625 | 626 | return pretty._safe_repr(obj) |
|
626 | 627 | else: |
|
627 | 628 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
628 | 629 | stream = StringIO() |
|
629 | 630 | # self.newline.encode() is a quick fix for issue gh-597. We need to |
|
630 | 631 | # ensure that stream does not get a mix of unicode and bytestrings, |
|
631 | 632 | # or it will cause trouble. |
|
632 | 633 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
633 | 634 | self.max_width, unicode_to_str(self.newline), |
|
634 | 635 | singleton_pprinters=self.singleton_printers, |
|
635 | 636 | type_pprinters=self.type_printers, |
|
636 | 637 | deferred_pprinters=self.deferred_printers) |
|
637 | 638 | printer.pretty(obj) |
|
638 | 639 | printer.flush() |
|
639 | 640 | return stream.getvalue() |
|
640 | 641 | |
|
641 | 642 | |
|
642 | 643 | class HTMLFormatter(BaseFormatter): |
|
643 | 644 | """An HTML formatter. |
|
644 | 645 | |
|
645 | 646 | To define the callables that compute the HTML representation of your |
|
646 | 647 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
647 | 648 | or :meth:`for_type_by_name` methods to register functions that handle |
|
648 | 649 | this. |
|
649 | 650 | |
|
650 | 651 | The return value of this formatter should be a valid HTML snippet that |
|
651 | 652 | could be injected into an existing DOM. It should *not* include the |
|
652 | 653 | ```<html>`` or ```<body>`` tags. |
|
653 | 654 | """ |
|
654 | 655 | format_type = Unicode('text/html') |
|
655 | 656 | |
|
656 | 657 | print_method = ObjectName('_repr_html_') |
|
657 | 658 | |
|
658 | 659 | |
|
659 | 660 | class SVGFormatter(BaseFormatter): |
|
660 | 661 | """An SVG formatter. |
|
661 | 662 | |
|
662 | 663 | To define the callables that compute the SVG representation of your |
|
663 | 664 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
664 | 665 | or :meth:`for_type_by_name` methods to register functions that handle |
|
665 | 666 | this. |
|
666 | 667 | |
|
667 | 668 | The return value of this formatter should be valid SVG enclosed in |
|
668 | 669 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
669 | 670 | *not* include the ```<html>`` or ```<body>`` tags. |
|
670 | 671 | """ |
|
671 | 672 | format_type = Unicode('image/svg+xml') |
|
672 | 673 | |
|
673 | 674 | print_method = ObjectName('_repr_svg_') |
|
674 | 675 | |
|
675 | 676 | |
|
676 | 677 | class PNGFormatter(BaseFormatter): |
|
677 | 678 | """A PNG formatter. |
|
678 | 679 | |
|
679 | 680 | To define the callables that compute the PNG representation of your |
|
680 | 681 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
681 | 682 | or :meth:`for_type_by_name` methods to register functions that handle |
|
682 | 683 | this. |
|
683 | 684 | |
|
684 | 685 | The return value of this formatter should be raw PNG data, *not* |
|
685 | 686 | base64 encoded. |
|
686 | 687 | """ |
|
687 | 688 | format_type = Unicode('image/png') |
|
688 | 689 | |
|
689 | 690 | print_method = ObjectName('_repr_png_') |
|
690 | 691 | |
|
691 | 692 | _return_type = bytes |
|
692 | 693 | |
|
693 | 694 | |
|
694 | 695 | class JPEGFormatter(BaseFormatter): |
|
695 | 696 | """A JPEG formatter. |
|
696 | 697 | |
|
697 | 698 | To define the callables that compute the JPEG representation of your |
|
698 | 699 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
699 | 700 | or :meth:`for_type_by_name` methods to register functions that handle |
|
700 | 701 | this. |
|
701 | 702 | |
|
702 | 703 | The return value of this formatter should be raw JPEG data, *not* |
|
703 | 704 | base64 encoded. |
|
704 | 705 | """ |
|
705 | 706 | format_type = Unicode('image/jpeg') |
|
706 | 707 | |
|
707 | 708 | print_method = ObjectName('_repr_jpeg_') |
|
708 | 709 | |
|
709 | 710 | _return_type = bytes |
|
710 | 711 | |
|
711 | 712 | |
|
712 | 713 | class LatexFormatter(BaseFormatter): |
|
713 | 714 | """A LaTeX formatter. |
|
714 | 715 | |
|
715 | 716 | To define the callables that compute the LaTeX representation of your |
|
716 | 717 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
717 | 718 | or :meth:`for_type_by_name` methods to register functions that handle |
|
718 | 719 | this. |
|
719 | 720 | |
|
720 | 721 | The return value of this formatter should be a valid LaTeX equation, |
|
721 | 722 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
722 | 723 | environment. |
|
723 | 724 | """ |
|
724 | 725 | format_type = Unicode('text/latex') |
|
725 | 726 | |
|
726 | 727 | print_method = ObjectName('_repr_latex_') |
|
727 | 728 | |
|
728 | 729 | |
|
729 | 730 | class JSONFormatter(BaseFormatter): |
|
730 | 731 | """A JSON string formatter. |
|
731 | 732 | |
|
732 | 733 | To define the callables that compute the JSON string representation of |
|
733 | 734 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
734 | 735 | or :meth:`for_type_by_name` methods to register functions that handle |
|
735 | 736 | this. |
|
736 | 737 | |
|
737 | 738 | The return value of this formatter should be a valid JSON string. |
|
738 | 739 | """ |
|
739 | 740 | format_type = Unicode('application/json') |
|
740 | 741 | |
|
741 | 742 | print_method = ObjectName('_repr_json_') |
|
742 | 743 | |
|
743 | 744 | |
|
744 | 745 | class JavascriptFormatter(BaseFormatter): |
|
745 | 746 | """A Javascript formatter. |
|
746 | 747 | |
|
747 | 748 | To define the callables that compute the Javascript representation of |
|
748 | 749 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
749 | 750 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
750 | 751 | that handle this. |
|
751 | 752 | |
|
752 | 753 | The return value of this formatter should be valid Javascript code and |
|
753 | 754 | should *not* be enclosed in ```<script>``` tags. |
|
754 | 755 | """ |
|
755 | 756 | format_type = Unicode('application/javascript') |
|
756 | 757 | |
|
757 | 758 | print_method = ObjectName('_repr_javascript_') |
|
758 | 759 | |
|
759 | 760 | FormatterABC.register(BaseFormatter) |
|
760 | 761 | FormatterABC.register(PlainTextFormatter) |
|
761 | 762 | FormatterABC.register(HTMLFormatter) |
|
762 | 763 | FormatterABC.register(SVGFormatter) |
|
763 | 764 | FormatterABC.register(PNGFormatter) |
|
764 | 765 | FormatterABC.register(JPEGFormatter) |
|
765 | 766 | FormatterABC.register(LatexFormatter) |
|
766 | 767 | FormatterABC.register(JSONFormatter) |
|
767 | 768 | FormatterABC.register(JavascriptFormatter) |
|
768 | 769 | |
|
769 | 770 | |
|
770 | 771 | def format_display_data(obj, include=None, exclude=None): |
|
771 | 772 | """Return a format data dict for an object. |
|
772 | 773 | |
|
773 | 774 | By default all format types will be computed. |
|
774 | 775 | |
|
775 | 776 | The following MIME types are currently implemented: |
|
776 | 777 | |
|
777 | 778 | * text/plain |
|
778 | 779 | * text/html |
|
779 | 780 | * text/latex |
|
780 | 781 | * application/json |
|
781 | 782 | * application/javascript |
|
782 | 783 | * image/png |
|
783 | 784 | * image/jpeg |
|
784 | 785 | * image/svg+xml |
|
785 | 786 | |
|
786 | 787 | Parameters |
|
787 | 788 | ---------- |
|
788 | 789 | obj : object |
|
789 | 790 | The Python object whose format data will be computed. |
|
790 | 791 | |
|
791 | 792 | Returns |
|
792 | 793 | ------- |
|
793 | 794 | format_dict : dict |
|
794 | 795 | A dictionary of key/value pairs, one or each format that was |
|
795 | 796 | generated for the object. The keys are the format types, which |
|
796 | 797 | will usually be MIME type strings and the values and JSON'able |
|
797 | 798 | data structure containing the raw data for the representation in |
|
798 | 799 | that format. |
|
799 | 800 | include : list or tuple, optional |
|
800 | 801 | A list of format type strings (MIME types) to include in the |
|
801 | 802 | format data dict. If this is set *only* the format types included |
|
802 | 803 | in this list will be computed. |
|
803 | 804 | exclude : list or tuple, optional |
|
804 | 805 | A list of format type string (MIME types) to exclue in the format |
|
805 | 806 | data dict. If this is set all format types will be computed, |
|
806 | 807 | except for those included in this argument. |
|
807 | 808 | """ |
|
808 | 809 | from IPython.core.interactiveshell import InteractiveShell |
|
809 | 810 | |
|
810 | 811 | InteractiveShell.instance().display_formatter.format( |
|
811 | 812 | obj, |
|
812 | 813 | include, |
|
813 | 814 | exclude |
|
814 | 815 | ) |
|
815 | 816 |
General Comments 0
You need to be logged in to leave comments.
Login now