##// END OF EJS Templates
Some documentations about custom formatters
M Bussonnier -
Show More
@@ -1,1031 +1,1090
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 This module defines the base instances in order to implement custom
5 formatters/mimetypes
6 got objects:
7
8 As we want to see internal IPython working we are going to use the following
9 function to diaply objects instead of the normal print or display method:
10
11 >>> ip = get_ipython()
12 >>> ip.display_formatter.format(...)
13 ({'text/plain': 'Ellipsis'}, {})
14
15 This return a tuple with the mimebumdle for the current object, and the
16 associated metadata.
17
18
19 We can now define our own formatter and register it:
20
21
22 >>> from IPython.core.formatters import BaseFormatter, FormatterABC
23
24
25 >>> class LLMFormatter(BaseFormatter):
26 ...
27 ... format_type = 'x-vendor/llm'
28 ... print_method = '_repr_llm_'
29 ... _return_type = (dict, str)
30
31 >>> llm_formatter = LLMFormatter(parent=ip.display_formatter)
32
33 >>> ip.display_formatter.formatters[LLMFormatter.format_type] = llm_formatter
34
35 Now any class that define `_repr_llm_` will return a x-vendor/llm as part of
36 it's display data:
37
38 >>> class A:
39 ...
40 ... def _repr_llm_(self, *kwargs):
41 ... return 'This a A'
42 ...
43
44 >>> ip.display_formatter.format(A())
45 ({'text/plain': '<IPython.core.formatters.A at ...>', 'x-vendor/llm': 'This a A'}, {})
46
47 As usual, you can register methods for third party types (see
48 :ref:`third_party_formatting`)
49
50 >>> def llm_int(obj):
51 ... return 'This is the integer %s, in between %s and %s'%(obj, obj-1, obj+1)
52
53 >>> llm_formatter.for_type(int, llm_int)
54
55 >>> ip.display_formatter.format(42)
56 ({'text/plain': '42', 'x-vendor/llm': 'This is the integer 42, in between 41 and 43'}, {})
57
58
4 59 Inheritance diagram:
5 60
6 61 .. inheritance-diagram:: IPython.core.formatters
7 62 :parts: 3
8 63 """
9 64
10 65 # Copyright (c) IPython Development Team.
11 66 # Distributed under the terms of the Modified BSD License.
12 67
13 68 import abc
14 69 import sys
15 70 import traceback
16 71 import warnings
17 72 from io import StringIO
18 73
19 74 from decorator import decorator
20 75
21 76 from traitlets.config.configurable import Configurable
22 77 from .getipython import get_ipython
23 78 from ..utils.sentinel import Sentinel
24 79 from ..utils.dir2 import get_real_method
25 80 from ..lib import pretty
26 81 from traitlets import (
27 82 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 83 ForwardDeclaredInstance,
29 84 default, observe,
30 85 )
31 86
32 87 from typing import Any
33 88
34 89
35 90 class DisplayFormatter(Configurable):
36 91
37 92 active_types = List(Unicode(),
38 93 help="""List of currently active mime-types to display.
39 94 You can use this to set a white-list for formats to display.
40 95
41 96 Most users will not need to change this value.
42 """).tag(config=True)
97 """,
98 ).tag(config=True)
43 99
44 100 @default('active_types')
45 101 def _active_types_default(self):
46 102 return self.format_types
47 103
48 104 @observe('active_types')
49 105 def _active_types_changed(self, change):
50 106 for key, formatter in self.formatters.items():
51 107 if key in change['new']:
52 108 formatter.enabled = True
53 109 else:
54 110 formatter.enabled = False
55 111
56 112 ipython_display_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
57 113
58 114 @default("ipython_display_formatter")
59 115 def _default_formatter(self):
60 116 return IPythonDisplayFormatter(parent=self)
61 117
62 118 mimebundle_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
63 119
64 120 @default("mimebundle_formatter")
65 121 def _default_mime_formatter(self):
66 122 return MimeBundleFormatter(parent=self)
67 123
68 124 # A dict of formatter whose keys are format types (MIME types) and whose
69 125 # values are subclasses of BaseFormatter.
70 126 formatters = Dict()
71 127
72 128 @default("formatters")
73 129 def _formatters_default(self):
74 130 """Activate the default formatters."""
75 131 formatter_classes = [
76 132 PlainTextFormatter,
77 133 HTMLFormatter,
78 134 MarkdownFormatter,
79 135 SVGFormatter,
80 136 PNGFormatter,
81 137 PDFFormatter,
82 138 JPEGFormatter,
83 139 LatexFormatter,
84 140 JSONFormatter,
85 141 JavascriptFormatter
86 142 ]
87 143 d = {}
88 144 for cls in formatter_classes:
89 145 f = cls(parent=self)
90 146 d[f.format_type] = f
91 147 return d
92 148
93 149 def format(self, obj, include=None, exclude=None):
94 150 """Return a format data dict for an object.
95 151
96 152 By default all format types will be computed.
97 153
98 154 The following MIME types are usually implemented:
99 155
100 156 * text/plain
101 157 * text/html
102 158 * text/markdown
103 159 * text/latex
104 160 * application/json
105 161 * application/javascript
106 162 * application/pdf
107 163 * image/png
108 164 * image/jpeg
109 165 * image/svg+xml
110 166
111 167 Parameters
112 168 ----------
113 169 obj : object
114 170 The Python object whose format data will be computed.
115 171 include : list, tuple or set; optional
116 172 A list of format type strings (MIME types) to include in the
117 173 format data dict. If this is set *only* the format types included
118 174 in this list will be computed.
119 175 exclude : list, tuple or set; optional
120 176 A list of format type string (MIME types) to exclude in the format
121 177 data dict. If this is set all format types will be computed,
122 178 except for those included in this argument.
123 179 Mimetypes present in exclude will take precedence over the ones in include
124 180
125 181 Returns
126 182 -------
127 183 (format_dict, metadata_dict) : tuple of two dicts
128 184 format_dict is a dictionary of key/value pairs, one of each format that was
129 185 generated for the object. The keys are the format types, which
130 186 will usually be MIME type strings and the values and JSON'able
131 187 data structure containing the raw data for the representation in
132 188 that format.
133 189
134 190 metadata_dict is a dictionary of metadata about each mime-type output.
135 191 Its keys will be a strict subset of the keys in format_dict.
136 192
137 193 Notes
138 194 -----
139 195 If an object implement `_repr_mimebundle_` as well as various
140 196 `_repr_*_`, the data returned by `_repr_mimebundle_` will take
141 197 precedence and the corresponding `_repr_*_` for this mimetype will
142 198 not be called.
143 199
144 200 """
145 201 format_dict = {}
146 202 md_dict = {}
147 203
148 204 if self.ipython_display_formatter(obj):
149 205 # object handled itself, don't proceed
150 206 return {}, {}
151 207
152 208 format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude)
153 209
154 210 if format_dict or md_dict:
155 211 if include:
156 212 format_dict = {k:v for k,v in format_dict.items() if k in include}
157 213 md_dict = {k:v for k,v in md_dict.items() if k in include}
158 214 if exclude:
159 215 format_dict = {k:v for k,v in format_dict.items() if k not in exclude}
160 216 md_dict = {k:v for k,v in md_dict.items() if k not in exclude}
161 217
162 218 for format_type, formatter in self.formatters.items():
163 219 if format_type in format_dict:
164 220 # already got it from mimebundle, maybe don't render again.
165 221 # exception: manually registered per-mime renderer
166 222 # check priority:
167 223 # 1. user-registered per-mime formatter
168 224 # 2. mime-bundle (user-registered or repr method)
169 225 # 3. default per-mime formatter (e.g. repr method)
170 226 try:
171 227 formatter.lookup(obj)
172 228 except KeyError:
173 229 # no special formatter, use mime-bundle-provided value
174 230 continue
175 231 if include and format_type not in include:
176 232 continue
177 233 if exclude and format_type in exclude:
178 234 continue
179 235
180 236 md = None
181 237 try:
182 238 data = formatter(obj)
183 239 except:
184 240 # FIXME: log the exception
185 241 raise
186 242
187 243 # formatters can return raw data or (data, metadata)
188 244 if isinstance(data, tuple) and len(data) == 2:
189 245 data, md = data
190 246
191 247 if data is not None:
192 248 format_dict[format_type] = data
193 249 if md is not None:
194 250 md_dict[format_type] = md
195 251 return format_dict, md_dict
196 252
197 253 @property
198 254 def format_types(self):
199 255 """Return the format types (MIME types) of the active formatters."""
200 256 return list(self.formatters.keys())
201 257
202 258
203 259 #-----------------------------------------------------------------------------
204 260 # Formatters for specific format types (text, html, svg, etc.)
205 261 #-----------------------------------------------------------------------------
206 262
207 263
208 264 def _safe_repr(obj):
209 265 """Try to return a repr of an object
210 266
211 267 always returns a string, at least.
212 268 """
213 269 try:
214 270 return repr(obj)
215 271 except Exception as e:
216 272 return "un-repr-able object (%r)" % e
217 273
218 274
219 275 class FormatterWarning(UserWarning):
220 276 """Warning class for errors in formatters"""
221 277
222 278 @decorator
223 279 def catch_format_error(method, self, *args, **kwargs):
224 280 """show traceback on failed format call"""
225 281 try:
226 282 r = method(self, *args, **kwargs)
227 283 except NotImplementedError:
228 284 # don't warn on NotImplementedErrors
229 285 return self._check_return(None, args[0])
230 286 except Exception:
231 287 exc_info = sys.exc_info()
232 288 ip = get_ipython()
233 289 if ip is not None:
234 290 ip.showtraceback(exc_info)
235 291 else:
236 292 traceback.print_exception(*exc_info)
237 293 return self._check_return(None, args[0])
238 294 return self._check_return(r, args[0])
239 295
240 296
241 297 class FormatterABC(metaclass=abc.ABCMeta):
242 298 """ Abstract base class for Formatters.
243 299
244 300 A formatter is a callable class that is responsible for computing the
245 301 raw format data for a particular format type (MIME type). For example,
246 302 an HTML formatter would have a format type of `text/html` and would return
247 303 the HTML representation of the object when called.
248 304 """
249 305
250 306 # The format type of the data returned, usually a MIME type.
251 307 format_type = 'text/plain'
252 308
253 309 # Is the formatter enabled...
254 310 enabled = True
255 311
256 312 @abc.abstractmethod
257 313 def __call__(self, obj):
258 314 """Return a JSON'able representation of the object.
259 315
260 316 If the object cannot be formatted by this formatter,
261 317 warn and return None.
262 318 """
263 319 return repr(obj)
264 320
265 321
266 322 def _mod_name_key(typ):
267 323 """Return a (__module__, __name__) tuple for a type.
268 324
269 325 Used as key in Formatter.deferred_printers.
270 326 """
271 327 module = getattr(typ, '__module__', None)
272 328 name = getattr(typ, '__name__', None)
273 329 return (module, name)
274 330
275 331
276 332 def _get_type(obj):
277 333 """Return the type of an instance (old and new-style)"""
278 334 return getattr(obj, '__class__', None) or type(obj)
279 335
280 336
281 _raise_key_error = Sentinel('_raise_key_error', __name__,
337 _raise_key_error = Sentinel(
338 "_raise_key_error",
339 __name__,
282 340 """
283 341 Special value to raise a KeyError
284 342
285 343 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
286 """)
344 """,
345 )
287 346
288 347
289 348 class BaseFormatter(Configurable):
290 349 """A base formatter class that is configurable.
291 350
292 351 This formatter should usually be used as the base class of all formatters.
293 352 It is a traited :class:`Configurable` class and includes an extensible
294 353 API for users to determine how their objects are formatted. The following
295 354 logic is used to find a function to format an given object.
296 355
297 356 1. The object is introspected to see if it has a method with the name
298 357 :attr:`print_method`. If is does, that object is passed to that method
299 358 for formatting.
300 359 2. If no print method is found, three internal dictionaries are consulted
301 360 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
302 361 and :attr:`deferred_printers`.
303 362
304 363 Users should use these dictionaries to register functions that will be
305 364 used to compute the format data for their objects (if those objects don't
306 365 have the special print methods). The easiest way of using these
307 366 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
308 367 methods.
309 368
310 369 If no function/callable is found to compute the format data, ``None`` is
311 370 returned and this format type is not used.
312 371 """
313 372
314 373 format_type = Unicode("text/plain")
315 374 _return_type: Any = str
316 375
317 376 enabled = Bool(True).tag(config=True)
318 377
319 378 print_method = ObjectName('__repr__')
320 379
321 380 # The singleton printers.
322 381 # Maps the IDs of the builtin singleton objects to the format functions.
323 382 singleton_printers = Dict().tag(config=True)
324 383
325 384 # The type-specific printers.
326 385 # Map type objects to the format functions.
327 386 type_printers = Dict().tag(config=True)
328 387
329 388 # The deferred-import type-specific printers.
330 389 # Map (modulename, classname) pairs to the format functions.
331 390 deferred_printers = Dict().tag(config=True)
332 391
333 392 @catch_format_error
334 393 def __call__(self, obj):
335 394 """Compute the format for an object."""
336 395 if self.enabled:
337 396 # lookup registered printer
338 397 try:
339 398 printer = self.lookup(obj)
340 399 except KeyError:
341 400 pass
342 401 else:
343 402 return printer(obj)
344 403 # Finally look for special method names
345 404 method = get_real_method(obj, self.print_method)
346 405 if method is not None:
347 406 return method()
348 407 return None
349 408 else:
350 409 return None
351 410
352 411 def __contains__(self, typ):
353 412 """map in to lookup_by_type"""
354 413 try:
355 414 self.lookup_by_type(typ)
356 415 except KeyError:
357 416 return False
358 417 else:
359 418 return True
360 419
361 420 def _check_return(self, r, obj):
362 421 """Check that a return value is appropriate
363 422
364 423 Return the value if so, None otherwise, warning if invalid.
365 424 """
366 425 if r is None or isinstance(r, self._return_type) or \
367 426 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
368 427 return r
369 428 else:
370 429 warnings.warn(
371 430 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
372 431 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
373 432 FormatterWarning
374 433 )
375 434
376 435 def lookup(self, obj):
377 436 """Look up the formatter for a given instance.
378 437
379 438 Parameters
380 439 ----------
381 440 obj : object instance
382 441
383 442 Returns
384 443 -------
385 444 f : callable
386 445 The registered formatting callable for the type.
387 446
388 447 Raises
389 448 ------
390 449 KeyError if the type has not been registered.
391 450 """
392 451 # look for singleton first
393 452 obj_id = id(obj)
394 453 if obj_id in self.singleton_printers:
395 454 return self.singleton_printers[obj_id]
396 455 # then lookup by type
397 456 return self.lookup_by_type(_get_type(obj))
398 457
399 458 def lookup_by_type(self, typ):
400 459 """Look up the registered formatter for a type.
401 460
402 461 Parameters
403 462 ----------
404 463 typ : type or '__module__.__name__' string for a type
405 464
406 465 Returns
407 466 -------
408 467 f : callable
409 468 The registered formatting callable for the type.
410 469
411 470 Raises
412 471 ------
413 472 KeyError if the type has not been registered.
414 473 """
415 474 if isinstance(typ, str):
416 475 typ_key = tuple(typ.rsplit('.',1))
417 476 if typ_key not in self.deferred_printers:
418 477 # We may have it cached in the type map. We will have to
419 478 # iterate over all of the types to check.
420 479 for cls in self.type_printers:
421 480 if _mod_name_key(cls) == typ_key:
422 481 return self.type_printers[cls]
423 482 else:
424 483 return self.deferred_printers[typ_key]
425 484 else:
426 485 for cls in pretty._get_mro(typ):
427 486 if cls in self.type_printers or self._in_deferred_types(cls):
428 487 return self.type_printers[cls]
429 488
430 489 # If we have reached here, the lookup failed.
431 490 raise KeyError("No registered printer for {0!r}".format(typ))
432 491
433 492 def for_type(self, typ, func=None):
434 493 """Add a format function for a given type.
435 494
436 495 Parameters
437 496 ----------
438 497 typ : type or '__module__.__name__' string for a type
439 498 The class of the object that will be formatted using `func`.
440 499
441 500 func : callable
442 501 A callable for computing the format data.
443 502 `func` will be called with the object to be formatted,
444 503 and will return the raw data in this formatter's format.
445 504 Subclasses may use a different call signature for the
446 505 `func` argument.
447 506
448 507 If `func` is None or not specified, there will be no change,
449 508 only returning the current value.
450 509
451 510 Returns
452 511 -------
453 512 oldfunc : callable
454 513 The currently registered callable.
455 514 If you are registering a new formatter,
456 515 this will be the previous value (to enable restoring later).
457 516 """
458 517 # if string given, interpret as 'pkg.module.class_name'
459 518 if isinstance(typ, str):
460 519 type_module, type_name = typ.rsplit('.', 1)
461 520 return self.for_type_by_name(type_module, type_name, func)
462 521
463 522 try:
464 523 oldfunc = self.lookup_by_type(typ)
465 524 except KeyError:
466 525 oldfunc = None
467 526
468 527 if func is not None:
469 528 self.type_printers[typ] = func
470 529
471 530 return oldfunc
472 531
473 532 def for_type_by_name(self, type_module, type_name, func=None):
474 533 """Add a format function for a type specified by the full dotted
475 534 module and name of the type, rather than the type of the object.
476 535
477 536 Parameters
478 537 ----------
479 538 type_module : str
480 539 The full dotted name of the module the type is defined in, like
481 540 ``numpy``.
482 541
483 542 type_name : str
484 543 The name of the type (the class name), like ``dtype``
485 544
486 545 func : callable
487 546 A callable for computing the format data.
488 547 `func` will be called with the object to be formatted,
489 548 and will return the raw data in this formatter's format.
490 549 Subclasses may use a different call signature for the
491 550 `func` argument.
492 551
493 552 If `func` is None or unspecified, there will be no change,
494 553 only returning the current value.
495 554
496 555 Returns
497 556 -------
498 557 oldfunc : callable
499 558 The currently registered callable.
500 559 If you are registering a new formatter,
501 560 this will be the previous value (to enable restoring later).
502 561 """
503 562 key = (type_module, type_name)
504 563
505 564 try:
506 565 oldfunc = self.lookup_by_type("%s.%s" % key)
507 566 except KeyError:
508 567 oldfunc = None
509 568
510 569 if func is not None:
511 570 self.deferred_printers[key] = func
512 571 return oldfunc
513 572
514 573 def pop(self, typ, default=_raise_key_error):
515 574 """Pop a formatter for the given type.
516 575
517 576 Parameters
518 577 ----------
519 578 typ : type or '__module__.__name__' string for a type
520 579 default : object
521 580 value to be returned if no formatter is registered for typ.
522 581
523 582 Returns
524 583 -------
525 584 obj : object
526 585 The last registered object for the type.
527 586
528 587 Raises
529 588 ------
530 589 KeyError if the type is not registered and default is not specified.
531 590 """
532 591
533 592 if isinstance(typ, str):
534 593 typ_key = tuple(typ.rsplit('.',1))
535 594 if typ_key not in self.deferred_printers:
536 595 # We may have it cached in the type map. We will have to
537 596 # iterate over all of the types to check.
538 597 for cls in self.type_printers:
539 598 if _mod_name_key(cls) == typ_key:
540 599 old = self.type_printers.pop(cls)
541 600 break
542 601 else:
543 602 old = default
544 603 else:
545 604 old = self.deferred_printers.pop(typ_key)
546 605 else:
547 606 if typ in self.type_printers:
548 607 old = self.type_printers.pop(typ)
549 608 else:
550 609 old = self.deferred_printers.pop(_mod_name_key(typ), default)
551 610 if old is _raise_key_error:
552 611 raise KeyError("No registered value for {0!r}".format(typ))
553 612 return old
554 613
555 614 def _in_deferred_types(self, cls):
556 615 """
557 616 Check if the given class is specified in the deferred type registry.
558 617
559 618 Successful matches will be moved to the regular type registry for future use.
560 619 """
561 620 mod = getattr(cls, '__module__', None)
562 621 name = getattr(cls, '__name__', None)
563 622 key = (mod, name)
564 623 if key in self.deferred_printers:
565 624 # Move the printer over to the regular registry.
566 625 printer = self.deferred_printers.pop(key)
567 626 self.type_printers[cls] = printer
568 627 return True
569 628 return False
570 629
571 630
572 631 class PlainTextFormatter(BaseFormatter):
573 632 """The default pretty-printer.
574 633
575 634 This uses :mod:`IPython.lib.pretty` to compute the format data of
576 635 the object. If the object cannot be pretty printed, :func:`repr` is used.
577 636 See the documentation of :mod:`IPython.lib.pretty` for details on
578 637 how to write pretty printers. Here is a simple example::
579 638
580 639 def dtype_pprinter(obj, p, cycle):
581 640 if cycle:
582 641 return p.text('dtype(...)')
583 642 if hasattr(obj, 'fields'):
584 643 if obj.fields is None:
585 644 p.text(repr(obj))
586 645 else:
587 646 p.begin_group(7, 'dtype([')
588 647 for i, field in enumerate(obj.descr):
589 648 if i > 0:
590 649 p.text(',')
591 650 p.breakable()
592 651 p.pretty(field)
593 652 p.end_group(7, '])')
594 653 """
595 654
596 655 # The format type of data returned.
597 656 format_type = Unicode('text/plain')
598 657
599 658 # This subclass ignores this attribute as it always need to return
600 659 # something.
601 660 enabled = Bool(True).tag(config=False)
602 661
603 662 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
604 663 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
605 664
606 665 Set to 0 to disable truncation.
607 """
666 """,
608 667 ).tag(config=True)
609 668
610 669 # Look for a _repr_pretty_ methods to use for pretty printing.
611 670 print_method = ObjectName('_repr_pretty_')
612 671
613 672 # Whether to pretty-print or not.
614 673 pprint = Bool(True).tag(config=True)
615 674
616 675 # Whether to be verbose or not.
617 676 verbose = Bool(False).tag(config=True)
618 677
619 678 # The maximum width.
620 679 max_width = Integer(79).tag(config=True)
621 680
622 681 # The newline character.
623 682 newline = Unicode('\n').tag(config=True)
624 683
625 684 # format-string for pprinting floats
626 685 float_format = Unicode('%r')
627 686 # setter for float precision, either int or direct format-string
628 687 float_precision = CUnicode('').tag(config=True)
629 688
630 689 @observe('float_precision')
631 690 def _float_precision_changed(self, change):
632 691 """float_precision changed, set float_format accordingly.
633 692
634 693 float_precision can be set by int or str.
635 694 This will set float_format, after interpreting input.
636 695 If numpy has been imported, numpy print precision will also be set.
637 696
638 697 integer `n` sets format to '%.nf', otherwise, format set directly.
639 698
640 699 An empty string returns to defaults (repr for float, 8 for numpy).
641 700
642 701 This parameter can be set via the '%precision' magic.
643 702 """
644 703 new = change['new']
645 704 if '%' in new:
646 705 # got explicit format string
647 706 fmt = new
648 707 try:
649 708 fmt%3.14159
650 709 except Exception as e:
651 710 raise ValueError("Precision must be int or format string, not %r"%new) from e
652 711 elif new:
653 712 # otherwise, should be an int
654 713 try:
655 714 i = int(new)
656 715 assert i >= 0
657 716 except ValueError as e:
658 717 raise ValueError("Precision must be int or format string, not %r"%new) from e
659 718 except AssertionError as e:
660 719 raise ValueError("int precision must be non-negative, not %r"%i) from e
661 720
662 721 fmt = '%%.%if'%i
663 722 if 'numpy' in sys.modules:
664 723 # set numpy precision if it has been imported
665 724 import numpy
666 725 numpy.set_printoptions(precision=i)
667 726 else:
668 727 # default back to repr
669 728 fmt = '%r'
670 729 if 'numpy' in sys.modules:
671 730 import numpy
672 731 # numpy default is 8
673 732 numpy.set_printoptions(precision=8)
674 733 self.float_format = fmt
675 734
676 735 # Use the default pretty printers from IPython.lib.pretty.
677 736 @default('singleton_printers')
678 737 def _singleton_printers_default(self):
679 738 return pretty._singleton_pprinters.copy()
680 739
681 740 @default('type_printers')
682 741 def _type_printers_default(self):
683 742 d = pretty._type_pprinters.copy()
684 743 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
685 744 # if NumPy is used, set precision for its float64 type
686 745 if "numpy" in sys.modules:
687 746 import numpy
688 747
689 748 d[numpy.float64] = lambda obj, p, cycle: p.text(self.float_format % obj)
690 749 return d
691 750
692 751 @default('deferred_printers')
693 752 def _deferred_printers_default(self):
694 753 return pretty._deferred_type_pprinters.copy()
695 754
696 755 #### FormatterABC interface ####
697 756
698 757 @catch_format_error
699 758 def __call__(self, obj):
700 759 """Compute the pretty representation of the object."""
701 760 if not self.pprint:
702 761 return repr(obj)
703 762 else:
704 763 stream = StringIO()
705 764 printer = pretty.RepresentationPrinter(stream, self.verbose,
706 765 self.max_width, self.newline,
707 766 max_seq_length=self.max_seq_length,
708 767 singleton_pprinters=self.singleton_printers,
709 768 type_pprinters=self.type_printers,
710 769 deferred_pprinters=self.deferred_printers)
711 770 printer.pretty(obj)
712 771 printer.flush()
713 772 return stream.getvalue()
714 773
715 774
716 775 class HTMLFormatter(BaseFormatter):
717 776 """An HTML formatter.
718 777
719 778 To define the callables that compute the HTML representation of your
720 779 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
721 780 or :meth:`for_type_by_name` methods to register functions that handle
722 781 this.
723 782
724 783 The return value of this formatter should be a valid HTML snippet that
725 784 could be injected into an existing DOM. It should *not* include the
726 785 ```<html>`` or ```<body>`` tags.
727 786 """
728 787 format_type = Unicode('text/html')
729 788
730 789 print_method = ObjectName('_repr_html_')
731 790
732 791
733 792 class MarkdownFormatter(BaseFormatter):
734 793 """A Markdown formatter.
735 794
736 795 To define the callables that compute the Markdown representation of your
737 796 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
738 797 or :meth:`for_type_by_name` methods to register functions that handle
739 798 this.
740 799
741 800 The return value of this formatter should be a valid Markdown.
742 801 """
743 802 format_type = Unicode('text/markdown')
744 803
745 804 print_method = ObjectName('_repr_markdown_')
746 805
747 806 class SVGFormatter(BaseFormatter):
748 807 """An SVG formatter.
749 808
750 809 To define the callables that compute the SVG representation of your
751 810 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
752 811 or :meth:`for_type_by_name` methods to register functions that handle
753 812 this.
754 813
755 814 The return value of this formatter should be valid SVG enclosed in
756 815 ```<svg>``` tags, that could be injected into an existing DOM. It should
757 816 *not* include the ```<html>`` or ```<body>`` tags.
758 817 """
759 818 format_type = Unicode('image/svg+xml')
760 819
761 820 print_method = ObjectName('_repr_svg_')
762 821
763 822
764 823 class PNGFormatter(BaseFormatter):
765 824 """A PNG formatter.
766 825
767 826 To define the callables that compute the PNG representation of your
768 827 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
769 828 or :meth:`for_type_by_name` methods to register functions that handle
770 829 this.
771 830
772 831 The return value of this formatter should be raw PNG data, *not*
773 832 base64 encoded.
774 833 """
775 834 format_type = Unicode('image/png')
776 835
777 836 print_method = ObjectName('_repr_png_')
778 837
779 838 _return_type = (bytes, str)
780 839
781 840
782 841 class JPEGFormatter(BaseFormatter):
783 842 """A JPEG formatter.
784 843
785 844 To define the callables that compute the JPEG representation of your
786 845 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
787 846 or :meth:`for_type_by_name` methods to register functions that handle
788 847 this.
789 848
790 849 The return value of this formatter should be raw JPEG data, *not*
791 850 base64 encoded.
792 851 """
793 852 format_type = Unicode('image/jpeg')
794 853
795 854 print_method = ObjectName('_repr_jpeg_')
796 855
797 856 _return_type = (bytes, str)
798 857
799 858
800 859 class LatexFormatter(BaseFormatter):
801 860 """A LaTeX formatter.
802 861
803 862 To define the callables that compute the LaTeX representation of your
804 863 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
805 864 or :meth:`for_type_by_name` methods to register functions that handle
806 865 this.
807 866
808 867 The return value of this formatter should be a valid LaTeX equation,
809 868 enclosed in either ```$```, ```$$``` or another LaTeX equation
810 869 environment.
811 870 """
812 871 format_type = Unicode('text/latex')
813 872
814 873 print_method = ObjectName('_repr_latex_')
815 874
816 875
817 876 class JSONFormatter(BaseFormatter):
818 877 """A JSON string formatter.
819 878
820 879 To define the callables that compute the JSONable representation of
821 880 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
822 881 or :meth:`for_type_by_name` methods to register functions that handle
823 882 this.
824 883
825 884 The return value of this formatter should be a JSONable list or dict.
826 885 JSON scalars (None, number, string) are not allowed, only dict or list containers.
827 886 """
828 887 format_type = Unicode('application/json')
829 888 _return_type = (list, dict)
830 889
831 890 print_method = ObjectName('_repr_json_')
832 891
833 892 def _check_return(self, r, obj):
834 893 """Check that a return value is appropriate
835 894
836 895 Return the value if so, None otherwise, warning if invalid.
837 896 """
838 897 if r is None:
839 898 return
840 899 md = None
841 900 if isinstance(r, tuple):
842 901 # unpack data, metadata tuple for type checking on first element
843 902 r, md = r
844 903
845 904 assert not isinstance(
846 905 r, str
847 906 ), "JSON-as-string has been deprecated since IPython < 3"
848 907
849 908 if md is not None:
850 909 # put the tuple back together
851 910 r = (r, md)
852 911 return super(JSONFormatter, self)._check_return(r, obj)
853 912
854 913
855 914 class JavascriptFormatter(BaseFormatter):
856 915 """A Javascript formatter.
857 916
858 917 To define the callables that compute the Javascript representation of
859 918 your objects, define a :meth:`_repr_javascript_` method or use the
860 919 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
861 920 that handle this.
862 921
863 922 The return value of this formatter should be valid Javascript code and
864 923 should *not* be enclosed in ```<script>``` tags.
865 924 """
866 925 format_type = Unicode('application/javascript')
867 926
868 927 print_method = ObjectName('_repr_javascript_')
869 928
870 929
871 930 class PDFFormatter(BaseFormatter):
872 931 """A PDF formatter.
873 932
874 933 To define the callables that compute the PDF representation of your
875 934 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
876 935 or :meth:`for_type_by_name` methods to register functions that handle
877 936 this.
878 937
879 938 The return value of this formatter should be raw PDF data, *not*
880 939 base64 encoded.
881 940 """
882 941 format_type = Unicode('application/pdf')
883 942
884 943 print_method = ObjectName('_repr_pdf_')
885 944
886 945 _return_type = (bytes, str)
887 946
888 947 class IPythonDisplayFormatter(BaseFormatter):
889 948 """An escape-hatch Formatter for objects that know how to display themselves.
890 949
891 950 To define the callables that compute the representation of your
892 951 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
893 952 or :meth:`for_type_by_name` methods to register functions that handle
894 953 this. Unlike mime-type displays, this method should not return anything,
895 954 instead calling any appropriate display methods itself.
896 955
897 956 This display formatter has highest priority.
898 957 If it fires, no other display formatter will be called.
899 958
900 959 Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types
901 960 without registering a new Formatter.
902 961
903 962 IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types,
904 963 so `_ipython_display_` should only be used for objects that require unusual
905 964 display patterns, such as multiple display calls.
906 965 """
907 966 print_method = ObjectName('_ipython_display_')
908 967 _return_type = (type(None), bool)
909 968
910 969 @catch_format_error
911 970 def __call__(self, obj):
912 971 """Compute the format for an object."""
913 972 if self.enabled:
914 973 # lookup registered printer
915 974 try:
916 975 printer = self.lookup(obj)
917 976 except KeyError:
918 977 pass
919 978 else:
920 979 printer(obj)
921 980 return True
922 981 # Finally look for special method names
923 982 method = get_real_method(obj, self.print_method)
924 983 if method is not None:
925 984 method()
926 985 return True
927 986
928 987
929 988 class MimeBundleFormatter(BaseFormatter):
930 989 """A Formatter for arbitrary mime-types.
931 990
932 991 Unlike other `_repr_<mimetype>_` methods,
933 992 `_repr_mimebundle_` should return mime-bundle data,
934 993 either the mime-keyed `data` dictionary or the tuple `(data, metadata)`.
935 994 Any mime-type is valid.
936 995
937 996 To define the callables that compute the mime-bundle representation of your
938 997 objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type`
939 998 or :meth:`for_type_by_name` methods to register functions that handle
940 999 this.
941 1000
942 1001 .. versionadded:: 6.1
943 1002 """
944 1003 print_method = ObjectName('_repr_mimebundle_')
945 1004 _return_type = dict
946 1005
947 1006 def _check_return(self, r, obj):
948 1007 r = super(MimeBundleFormatter, self)._check_return(r, obj)
949 1008 # always return (data, metadata):
950 1009 if r is None:
951 1010 return {}, {}
952 1011 if not isinstance(r, tuple):
953 1012 return r, {}
954 1013 return r
955 1014
956 1015 @catch_format_error
957 1016 def __call__(self, obj, include=None, exclude=None):
958 1017 """Compute the format for an object.
959 1018
960 1019 Identical to parent's method but we pass extra parameters to the method.
961 1020
962 1021 Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in
963 1022 particular `include` and `exclude`.
964 1023 """
965 1024 if self.enabled:
966 1025 # lookup registered printer
967 1026 try:
968 1027 printer = self.lookup(obj)
969 1028 except KeyError:
970 1029 pass
971 1030 else:
972 1031 return printer(obj)
973 1032 # Finally look for special method names
974 1033 method = get_real_method(obj, self.print_method)
975 1034
976 1035 if method is not None:
977 1036 return method(include=include, exclude=exclude)
978 1037 return None
979 1038 else:
980 1039 return None
981 1040
982 1041
983 1042 FormatterABC.register(BaseFormatter)
984 1043 FormatterABC.register(PlainTextFormatter)
985 1044 FormatterABC.register(HTMLFormatter)
986 1045 FormatterABC.register(MarkdownFormatter)
987 1046 FormatterABC.register(SVGFormatter)
988 1047 FormatterABC.register(PNGFormatter)
989 1048 FormatterABC.register(PDFFormatter)
990 1049 FormatterABC.register(JPEGFormatter)
991 1050 FormatterABC.register(LatexFormatter)
992 1051 FormatterABC.register(JSONFormatter)
993 1052 FormatterABC.register(JavascriptFormatter)
994 1053 FormatterABC.register(IPythonDisplayFormatter)
995 1054 FormatterABC.register(MimeBundleFormatter)
996 1055
997 1056
998 1057 def format_display_data(obj, include=None, exclude=None):
999 1058 """Return a format data dict for an object.
1000 1059
1001 1060 By default all format types will be computed.
1002 1061
1003 1062 Parameters
1004 1063 ----------
1005 1064 obj : object
1006 1065 The Python object whose format data will be computed.
1007 1066
1008 1067 Returns
1009 1068 -------
1010 1069 format_dict : dict
1011 1070 A dictionary of key/value pairs, one or each format that was
1012 1071 generated for the object. The keys are the format types, which
1013 1072 will usually be MIME type strings and the values and JSON'able
1014 1073 data structure containing the raw data for the representation in
1015 1074 that format.
1016 1075 include : list or tuple, optional
1017 1076 A list of format type strings (MIME types) to include in the
1018 1077 format data dict. If this is set *only* the format types included
1019 1078 in this list will be computed.
1020 1079 exclude : list or tuple, optional
1021 1080 A list of format type string (MIME types) to exclude in the format
1022 1081 data dict. If this is set all format types will be computed,
1023 1082 except for those included in this argument.
1024 1083 """
1025 1084 from .interactiveshell import InteractiveShell
1026 1085
1027 1086 return InteractiveShell.instance().display_formatter.format(
1028 1087 obj,
1029 1088 include,
1030 1089 exclude
1031 1090 )
@@ -1,184 +1,186
1 1 .. _integrating:
2 2
3 3 =====================================
4 4 Integrating your objects with IPython
5 5 =====================================
6 6
7 7 Tab completion
8 8 ==============
9 9
10 10 To change the attributes displayed by tab-completing your object, define a
11 11 ``__dir__(self)`` method for it. For more details, see the documentation of the
12 built-in `dir() function <http://docs.python.org/library/functions.html#dir>`_.
12 built-in :external+python:py:func:`dir`
13 13
14 14 You can also customise key completions for your objects, e.g. pressing tab after
15 15 ``obj["a``. To do so, define a method ``_ipython_key_completions_()``, which
16 16 returns a list of objects which are possible keys in a subscript expression
17 17 ``obj[key]``.
18 18
19 19 .. versionadded:: 5.0
20 20 Custom key completions
21 21
22 22 .. _integrating_rich_display:
23 23
24 24 Rich display
25 25 ============
26 26
27 27 Custom methods
28 ----------------------
28 --------------
29 29
30 30 IPython can display richer representations of objects.
31 31 To do this, you can define ``_ipython_display_()``, or any of a number of
32 32 ``_repr_*_()`` methods.
33 33 Note that these are surrounded by single, not double underscores.
34 34
35 35
36 36 .. list-table:: Supported ``_repr_*_`` methods
37 37 :widths: 20 15 15 15
38 38 :header-rows: 1
39 39
40 40 * - Format
41 41 - REPL
42 42 - Notebook
43 43 - Qt Console
44 44 * - ``_repr_pretty_``
45 45 - yes
46 46 - yes
47 47 - yes
48 48 * - ``_repr_svg_``
49 49 - no
50 50 - yes
51 51 - yes
52 52 * - ``_repr_png_``
53 53 - no
54 54 - yes
55 55 - yes
56 56 * - ``_repr_jpeg_``
57 57 - no
58 58 - yes
59 59 - yes
60 60 * - ``_repr_html_``
61 61 - no
62 62 - yes
63 63 - no
64 64 * - ``_repr_javascript_``
65 65 - no
66 66 - yes
67 67 - no
68 68 * - ``_repr_markdown_``
69 69 - no
70 70 - yes
71 71 - no
72 72 * - ``_repr_latex_``
73 73 - no
74 74 - yes
75 75 - no
76 76 * - ``_repr_mimebundle_``
77 77 - no
78 78 - ?
79 79 - ?
80 80
81 81 If the methods don't exist, the standard ``repr()`` is used.
82 82 If a method exists and returns ``None``, it is treated the same as if it does not exist.
83 83 In general, *all* available formatters will be called when an object is displayed,
84 84 and it is up to the UI to select which to display.
85 85 A given formatter should not generally change its output based on what other formats are available -
86 86 that should be handled at a different level, such as the :class:`~.DisplayFormatter`, or configuration.
87 87
88 88 ``_repr_*_`` methods should *return* data of the expected format and have no side effects.
89 89 For example, ``_repr_html_`` should return HTML as a `str` and ``_repr_png_`` should return PNG data as `bytes`.
90 90
91 91 If you wish to take control of display via your own side effects, use ``_ipython_display_()``.
92 92
93 93 For example::
94 94
95 95 class Shout(object):
96 96 def __init__(self, text):
97 97 self.text = text
98 98
99 99 def _repr_html_(self):
100 100 return "<h1>" + self.text + "</h1>"
101 101
102 102
103 103 Special methods
104 104 ^^^^^^^^^^^^^^^
105 105
106 106 Pretty printing
107 107 """""""""""""""
108 108
109 109 To customize how your object is pretty-printed, add a ``_repr_pretty_`` method
110 110 to the class.
111 111 The method should accept a pretty printer, and a boolean that indicates whether
112 112 the printer detected a cycle.
113 113 The method should act on the printer to produce your customized pretty output.
114 114 Here is an example::
115 115
116 116 class MyObject(object):
117 117
118 118 def _repr_pretty_(self, p, cycle):
119 119 if cycle:
120 120 p.text('MyObject(...)')
121 121 else:
122 122 p.text('MyObject[...]')
123 123
124 124 For details on how to use the pretty printer, see :py:mod:`IPython.lib.pretty`.
125 125
126 126 More powerful methods
127 127 """""""""""""""""""""
128 128
129 129 .. class:: MyObject
130 130
131 131 .. method:: _repr_mimebundle_(include=None, exclude=None)
132 132
133 133 Should return a dictionary of multiple formats, keyed by mimetype, or a tuple
134 134 of two dictionaries: *data, metadata* (see :ref:`Metadata`).
135 135 If this returns something, other ``_repr_*_`` methods are ignored.
136 136 The method should take keyword arguments ``include`` and ``exclude``, though
137 137 it is not required to respect them.
138 138
139 139 .. method:: _ipython_display_()
140 140
141 141 Displays the object as a side effect; the return value is ignored. If this
142 142 is defined, all other display methods are ignored.
143 143
144 144
145 145 Metadata
146 146 ^^^^^^^^
147 147
148 148 We often want to provide frontends with guidance on how to display the data. To
149 149 support this, ``_repr_*_()`` methods (except ``_repr_pretty_``?) can also return a ``(data, metadata)``
150 150 tuple where ``metadata`` is a dictionary containing arbitrary key-value pairs for
151 151 the frontend to interpret. An example use case is ``_repr_jpeg_()``, which can
152 152 be set to return a jpeg image and a ``{'height': 400, 'width': 600}`` dictionary
153 153 to inform the frontend how to size the image.
154 154
155 155
156 156
157 .. _third_party_formatting:
158
157 159 Formatters for third-party types
158 160 --------------------------------
159 161
160 162 The user can also register formatters for types without modifying the class::
161 163
162 164 from bar.baz import Foo
163 165
164 166 def foo_html(obj):
165 167 return '<marquee>Foo object %s</marquee>' % obj.name
166 168
167 169 html_formatter = get_ipython().display_formatter.formatters['text/html']
168 170 html_formatter.for_type(Foo, foo_html)
169 171
170 172 # Or register a type without importing it - this does the same as above:
171 173 html_formatter.for_type_by_name('bar.baz', 'Foo', foo_html)
172 174
173 175 Custom exception tracebacks
174 176 ===========================
175 177
176 178 Rarely, you might want to display a custom traceback when reporting an
177 179 exception. To do this, define the custom traceback using
178 180 `_render_traceback_(self)` method which returns a list of strings, one string
179 181 for each line of the traceback. For example, the `ipyparallel
180 182 <https://ipyparallel.readthedocs.io/>`__ a parallel computing framework for
181 183 IPython, does this to display errors from multiple engines.
182 184
183 185 Please be conservative in using this feature; by replacing the default traceback
184 186 you may hide important information from the user.
General Comments 0
You need to be logged in to leave comments. Login now