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