Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/IPython/core/formatters.py: 39%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

365 statements  

1"""Display formatters. 

2 

3This module defines the base instances in order to implement custom 

4formatters/mimetypes 

5got objects: 

6 

7As we want to see internal IPython working we are going to use the following 

8function to diaply objects instead of the normal print or display method: 

9 

10 >>> ip = get_ipython() 

11 >>> ip.display_formatter.format(...) 

12 ({'text/plain': 'Ellipsis'}, {}) 

13 

14This return a tuple with the mimebumdle for the current object, and the 

15associated metadata. 

16 

17 

18We can now define our own formatter and register it: 

19 

20 

21 >>> from IPython.core.formatters import BaseFormatter, FormatterABC 

22 

23 

24 >>> class LLMFormatter(BaseFormatter): 

25 ... 

26 ... format_type = 'x-vendor/llm' 

27 ... print_method = '_repr_llm_' 

28 ... _return_type = (dict, str) 

29 

30 >>> llm_formatter = LLMFormatter(parent=ip.display_formatter) 

31 

32 >>> ip.display_formatter.register_formatter(llm_formatter) 

33 

34Now any class that define `_repr_llm_` will return a x-vendor/llm as part of 

35it's display data: 

36 

37 >>> class A: 

38 ... 

39 ... def _repr_llm_(self, *kwargs): 

40 ... return 'This a A' 

41 ... 

42 

43 >>> ip.display_formatter.format(A()) 

44 ({'text/plain': '<IPython.core.formatters.A at ...>', 'x-vendor/llm': 'This a A'}, {}) 

45 

46As usual, you can register methods for third party types (see 

47:ref:`third_party_formatting`) 

48 

49 >>> def llm_int(obj): 

50 ... return 'This is the integer %s, in between %s and %s'%(obj, obj-1, obj+1) 

51 

52 >>> llm_formatter.for_type(int, llm_int) 

53 

54 >>> ip.display_formatter.format(42) 

55 ({'text/plain': '42', 'x-vendor/llm': 'This is the integer 42, in between 41 and 43'}, {}) 

56 

57 

58Inheritance diagram: 

59 

60.. inheritance-diagram:: IPython.core.formatters 

61 :parts: 3 

62""" 

63 

64# Copyright (c) IPython Development Team. 

65# Distributed under the terms of the Modified BSD License. 

66 

67import abc 

68import sys 

69import warnings 

70from io import StringIO 

71 

72from functools import wraps 

73 

74from traitlets.config.configurable import Configurable 

75from .getipython import get_ipython 

76from ..utils.sentinel import Sentinel 

77from ..utils.dir2 import get_real_method 

78from ..lib import pretty 

79from traitlets import ( 

80 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, 

81 ForwardDeclaredInstance, 

82 default, observe, 

83) 

84 

85from typing import Any 

86 

87 

88class DisplayFormatter(Configurable): 

89 

90 active_types = List(Unicode(), 

91 help="""List of currently active mime-types to display. 

92 You can use this to set a white-list for formats to display. 

93 

94 Most users will not need to change this value. 

95 """, 

96 ).tag(config=True) 

97 

98 @default('active_types') 

99 def _active_types_default(self): 

100 return self.format_types 

101 

102 @observe('active_types') 

103 def _active_types_changed(self, change): 

104 for key, formatter in self.formatters.items(): 

105 if key in change['new']: 

106 formatter.enabled = True 

107 else: 

108 formatter.enabled = False 

109 

110 ipython_display_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore 

111 

112 @default("ipython_display_formatter") 

113 def _default_formatter(self): 

114 return IPythonDisplayFormatter(parent=self) 

115 

116 mimebundle_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore 

117 

118 @default("mimebundle_formatter") 

119 def _default_mime_formatter(self): 

120 return MimeBundleFormatter(parent=self) 

121 

122 # A dict of formatter whose keys are format types (MIME types) and whose 

123 # values are subclasses of BaseFormatter. 

124 formatters = Dict() 

125 

126 @default("formatters") 

127 def _formatters_default(self): 

128 """Activate the default formatters.""" 

129 formatter_classes = [ 

130 PlainTextFormatter, 

131 HTMLFormatter, 

132 MarkdownFormatter, 

133 SVGFormatter, 

134 PNGFormatter, 

135 PDFFormatter, 

136 JPEGFormatter, 

137 LatexFormatter, 

138 JSONFormatter, 

139 JavascriptFormatter 

140 ] 

141 d = {} 

142 for cls in formatter_classes: 

143 f = cls(parent=self) 

144 d[f.format_type] = f 

145 return d 

146 

147 def register_formatter(self, formatter): 

148 if formatter.format_type in self.formatters: 

149 warnings.warn( 

150 f"Replacing formatter {type(self.formatters[formatter.format_type])} with {type(formatter)}", 

151 FormatterWarning, 

152 ) 

153 self.formatters[formatter.format_type] = formatter 

154 

155 def format(self, obj, include=None, exclude=None): 

156 """Return a format data dict for an object. 

157 

158 By default all format types will be computed. 

159 

160 The following MIME types are usually implemented: 

161 

162 * text/plain 

163 * text/html 

164 * text/markdown 

165 * text/latex 

166 * application/json 

167 * application/javascript 

168 * application/pdf 

169 * image/png 

170 * image/jpeg 

171 * image/svg+xml 

172 

173 Parameters 

174 ---------- 

175 obj : object 

176 The Python object whose format data will be computed. 

177 include : list, tuple or set; optional 

178 A list of format type strings (MIME types) to include in the 

179 format data dict. If this is set *only* the format types included 

180 in this list will be computed. 

181 exclude : list, tuple or set; optional 

182 A list of format type string (MIME types) to exclude in the format 

183 data dict. If this is set all format types will be computed, 

184 except for those included in this argument. 

185 Mimetypes present in exclude will take precedence over the ones in include 

186 

187 Returns 

188 ------- 

189 (format_dict, metadata_dict) : tuple of two dicts 

190 format_dict is a dictionary of key/value pairs, one of each format that was 

191 generated for the object. The keys are the format types, which 

192 will usually be MIME type strings and the values and JSON'able 

193 data structure containing the raw data for the representation in 

194 that format. 

195 

196 metadata_dict is a dictionary of metadata about each mime-type output. 

197 Its keys will be a strict subset of the keys in format_dict. 

198 

199 Notes 

200 ----- 

201 If an object implement `_repr_mimebundle_` as well as various 

202 `_repr_*_`, the data returned by `_repr_mimebundle_` will take 

203 precedence and the corresponding `_repr_*_` for this mimetype will 

204 not be called. 

205 

206 """ 

207 format_dict = {} 

208 md_dict = {} 

209 

210 if self.ipython_display_formatter(obj): 

211 # object handled itself, don't proceed 

212 return {}, {} 

213 

214 format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude) 

215 

216 if format_dict or md_dict: 

217 if include: 

218 format_dict = {k:v for k,v in format_dict.items() if k in include} 

219 md_dict = {k:v for k,v in md_dict.items() if k in include} 

220 if exclude: 

221 format_dict = {k:v for k,v in format_dict.items() if k not in exclude} 

222 md_dict = {k:v for k,v in md_dict.items() if k not in exclude} 

223 

224 for format_type, formatter in self.formatters.items(): 

225 if format_type in format_dict: 

226 # already got it from mimebundle, maybe don't render again. 

227 # exception: manually registered per-mime renderer 

228 # check priority: 

229 # 1. user-registered per-mime formatter 

230 # 2. mime-bundle (user-registered or repr method) 

231 # 3. default per-mime formatter (e.g. repr method) 

232 try: 

233 formatter.lookup(obj) 

234 except KeyError: 

235 # no special formatter, use mime-bundle-provided value 

236 continue 

237 if include and format_type not in include: 

238 continue 

239 if exclude and format_type in exclude: 

240 continue 

241 

242 md = None 

243 data = formatter(obj) 

244 

245 # formatters can return raw data or (data, metadata) 

246 if isinstance(data, tuple) and len(data) == 2: 

247 data, md = data 

248 

249 if data is not None: 

250 format_dict[format_type] = data 

251 if md is not None: 

252 md_dict[format_type] = md 

253 return format_dict, md_dict 

254 

255 @property 

256 def format_types(self): 

257 """Return the format types (MIME types) of the active formatters.""" 

258 return list(self.formatters.keys()) 

259 

260 

261#----------------------------------------------------------------------------- 

262# Formatters for specific format types (text, html, svg, etc.) 

263#----------------------------------------------------------------------------- 

264 

265 

266def _safe_repr(obj): 

267 """Try to return a repr of an object 

268 

269 always returns a string, at least. 

270 """ 

271 try: 

272 return repr(obj) 

273 except Exception as e: 

274 return "un-repr-able object (%r)" % e 

275 

276 

277class FormatterWarning(UserWarning): 

278 """Warning class for errors in formatters""" 

279 

280def catch_format_error(method): 

281 """show traceback on failed format call""" 

282 

283 @wraps(method) 

284 def wrapper(self, *args, **kwargs): 

285 try: 

286 r = method(self, *args, **kwargs) 

287 except NotImplementedError: 

288 # don't warn on NotImplementedErrors 

289 return self._check_return(None, args[0]) 

290 except Exception: 

291 exc_info = sys.exc_info() 

292 ip = get_ipython() 

293 if ip is not None: 

294 ip.showtraceback(exc_info) 

295 else: 

296 import traceback 

297 traceback.print_exception(*exc_info) 

298 return self._check_return(None, args[0]) 

299 return self._check_return(r, args[0]) 

300 

301 return wrapper 

302 

303 

304class FormatterABC(metaclass=abc.ABCMeta): 

305 """ Abstract base class for Formatters. 

306 

307 A formatter is a callable class that is responsible for computing the 

308 raw format data for a particular format type (MIME type). For example, 

309 an HTML formatter would have a format type of `text/html` and would return 

310 the HTML representation of the object when called. 

311 """ 

312 

313 # The format type of the data returned, usually a MIME type. 

314 format_type = 'text/plain' 

315 

316 # Is the formatter enabled... 

317 enabled = True 

318 

319 @abc.abstractmethod 

320 def __call__(self, obj): 

321 """Return a JSON'able representation of the object. 

322 

323 If the object cannot be formatted by this formatter, 

324 warn and return None. 

325 """ 

326 return repr(obj) 

327 

328 

329def _mod_name_key(typ): 

330 """Return a (__module__, __name__) tuple for a type. 

331 

332 Used as key in Formatter.deferred_printers. 

333 """ 

334 module = getattr(typ, '__module__', None) 

335 name = getattr(typ, '__name__', None) 

336 return (module, name) 

337 

338 

339def _get_type(obj): 

340 """Return the type of an instance (old and new-style)""" 

341 return getattr(obj, '__class__', None) or type(obj) 

342 

343 

344_raise_key_error = Sentinel( 

345 "_raise_key_error", 

346 __name__, 

347 """ 

348Special value to raise a KeyError 

349 

350Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop` 

351""", 

352) 

353 

354 

355class BaseFormatter(Configurable): 

356 """A base formatter class that is configurable. 

357 

358 This formatter should usually be used as the base class of all formatters. 

359 It is a traited :class:`Configurable` class and includes an extensible 

360 API for users to determine how their objects are formatted. The following 

361 logic is used to find a function to format an given object. 

362 

363 1. The object is introspected to see if it has a method with the name 

364 :attr:`print_method`. If is does, that object is passed to that method 

365 for formatting. 

366 2. If no print method is found, three internal dictionaries are consulted 

367 to find print method: :attr:`singleton_printers`, :attr:`type_printers` 

368 and :attr:`deferred_printers`. 

369 

370 Users should use these dictionaries to register functions that will be 

371 used to compute the format data for their objects (if those objects don't 

372 have the special print methods). The easiest way of using these 

373 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` 

374 methods. 

375 

376 If no function/callable is found to compute the format data, :py:data:`None` is 

377 returned and this format type is not used. 

378 """ 

379 

380 format_type = Unicode("text/plain") 

381 _return_type: Any = str 

382 

383 enabled = Bool(True).tag(config=True) 

384 

385 print_method = ObjectName('__repr__') 

386 

387 # The singleton printers. 

388 # Maps the IDs of the builtin singleton objects to the format functions. 

389 singleton_printers = Dict().tag(config=True) 

390 

391 # The type-specific printers. 

392 # Map type objects to the format functions. 

393 type_printers = Dict().tag(config=True) 

394 

395 # The deferred-import type-specific printers. 

396 # Map (modulename, classname) pairs to the format functions. 

397 deferred_printers = Dict().tag(config=True) 

398 

399 @catch_format_error 

400 def __call__(self, obj): 

401 """Compute the format for an object.""" 

402 if self.enabled: 

403 # lookup registered printer 

404 try: 

405 printer = self.lookup(obj) 

406 except KeyError: 

407 pass 

408 else: 

409 return printer(obj) 

410 # Finally look for special method names 

411 method = get_real_method(obj, self.print_method) 

412 if method is not None: 

413 return method() 

414 return None 

415 else: 

416 return None 

417 

418 def __contains__(self, typ): 

419 """map in to lookup_by_type""" 

420 try: 

421 self.lookup_by_type(typ) 

422 except KeyError: 

423 return False 

424 else: 

425 return True 

426 

427 def _check_return(self, r, obj): 

428 """Check that a return value is appropriate 

429 

430 Return the value if so, None otherwise, warning if invalid. 

431 """ 

432 if r is None or isinstance(r, self._return_type) or \ 

433 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): 

434 return r 

435 else: 

436 warnings.warn( 

437 "%s formatter returned invalid type %s (expected %s) for object: %s" % \ 

438 (self.format_type, type(r), self._return_type, _safe_repr(obj)), 

439 FormatterWarning 

440 ) 

441 

442 def lookup(self, obj): 

443 """Look up the formatter for a given instance. 

444 

445 Parameters 

446 ---------- 

447 obj : object instance 

448 

449 Returns 

450 ------- 

451 f : callable 

452 The registered formatting callable for the type. 

453 

454 Raises 

455 ------ 

456 KeyError if the type has not been registered. 

457 """ 

458 # look for singleton first 

459 obj_id = id(obj) 

460 if obj_id in self.singleton_printers: 

461 return self.singleton_printers[obj_id] 

462 # then lookup by type 

463 return self.lookup_by_type(_get_type(obj)) 

464 

465 def lookup_by_type(self, typ): 

466 """Look up the registered formatter for a type. 

467 

468 Parameters 

469 ---------- 

470 typ : type or '__module__.__name__' string for a type 

471 

472 Returns 

473 ------- 

474 f : callable 

475 The registered formatting callable for the type. 

476 

477 Raises 

478 ------ 

479 KeyError if the type has not been registered. 

480 """ 

481 if isinstance(typ, str): 

482 typ_key = tuple(typ.rsplit('.',1)) 

483 if typ_key not in self.deferred_printers: 

484 # We may have it cached in the type map. We will have to 

485 # iterate over all of the types to check. 

486 for cls in self.type_printers: 

487 if _mod_name_key(cls) == typ_key: 

488 return self.type_printers[cls] 

489 else: 

490 return self.deferred_printers[typ_key] 

491 else: 

492 for cls in pretty._get_mro(typ): 

493 if cls in self.type_printers or self._in_deferred_types(cls): 

494 return self.type_printers[cls] 

495 

496 # If we have reached here, the lookup failed. 

497 raise KeyError(f"No registered printer for {typ!r}") 

498 

499 def for_type(self, typ, func=None): 

500 """Add a format function for a given type. 

501 

502 Parameters 

503 ---------- 

504 typ : type or '__module__.__name__' string for a type 

505 The class of the object that will be formatted using `func`. 

506 

507 func : callable 

508 A callable for computing the format data. 

509 `func` will be called with the object to be formatted, 

510 and will return the raw data in this formatter's format. 

511 Subclasses may use a different call signature for the 

512 `func` argument. 

513 

514 If `func` is None or not specified, there will be no change, 

515 only returning the current value. 

516 

517 Returns 

518 ------- 

519 oldfunc : callable 

520 The currently registered callable. 

521 If you are registering a new formatter, 

522 this will be the previous value (to enable restoring later). 

523 """ 

524 # if string given, interpret as 'pkg.module.class_name' 

525 if isinstance(typ, str): 

526 type_module, type_name = typ.rsplit('.', 1) 

527 return self.for_type_by_name(type_module, type_name, func) 

528 

529 try: 

530 oldfunc = self.lookup_by_type(typ) 

531 except KeyError: 

532 oldfunc = None 

533 

534 if func is not None: 

535 self.type_printers[typ] = func 

536 

537 return oldfunc 

538 

539 def for_type_by_name(self, type_module, type_name, func=None): 

540 """Add a format function for a type specified by the full dotted 

541 module and name of the type, rather than the type of the object. 

542 

543 Parameters 

544 ---------- 

545 type_module : str 

546 The full dotted name of the module the type is defined in, like 

547 ``numpy``. 

548 

549 type_name : str 

550 The name of the type (the class name), like ``dtype`` 

551 

552 func : callable 

553 A callable for computing the format data. 

554 `func` will be called with the object to be formatted, 

555 and will return the raw data in this formatter's format. 

556 Subclasses may use a different call signature for the 

557 `func` argument. 

558 

559 If `func` is None or unspecified, there will be no change, 

560 only returning the current value. 

561 

562 Returns 

563 ------- 

564 oldfunc : callable 

565 The currently registered callable. 

566 If you are registering a new formatter, 

567 this will be the previous value (to enable restoring later). 

568 """ 

569 key = (type_module, type_name) 

570 

571 try: 

572 oldfunc = self.lookup_by_type("%s.%s" % key) 

573 except KeyError: 

574 oldfunc = None 

575 

576 if func is not None: 

577 self.deferred_printers[key] = func 

578 return oldfunc 

579 

580 def pop(self, typ, default=_raise_key_error): 

581 """Pop a formatter for the given type. 

582 

583 Parameters 

584 ---------- 

585 typ : type or '__module__.__name__' string for a type 

586 default : object 

587 value to be returned if no formatter is registered for typ. 

588 

589 Returns 

590 ------- 

591 obj : object 

592 The last registered object for the type. 

593 

594 Raises 

595 ------ 

596 KeyError if the type is not registered and default is not specified. 

597 """ 

598 

599 if isinstance(typ, str): 

600 typ_key = tuple(typ.rsplit('.',1)) 

601 if typ_key not in self.deferred_printers: 

602 # We may have it cached in the type map. We will have to 

603 # iterate over all of the types to check. 

604 for cls in self.type_printers: 

605 if _mod_name_key(cls) == typ_key: 

606 old = self.type_printers.pop(cls) 

607 break 

608 else: 

609 old = default 

610 else: 

611 old = self.deferred_printers.pop(typ_key) 

612 else: 

613 if typ in self.type_printers: 

614 old = self.type_printers.pop(typ) 

615 else: 

616 old = self.deferred_printers.pop(_mod_name_key(typ), default) 

617 if old is _raise_key_error: 

618 raise KeyError(f"No registered value for {typ!r}") 

619 return old 

620 

621 def _in_deferred_types(self, cls): 

622 """ 

623 Check if the given class is specified in the deferred type registry. 

624 

625 Successful matches will be moved to the regular type registry for future use. 

626 """ 

627 mod = getattr(cls, '__module__', None) 

628 name = getattr(cls, '__name__', None) 

629 key = (mod, name) 

630 if key in self.deferred_printers: 

631 # Move the printer over to the regular registry. 

632 printer = self.deferred_printers.pop(key) 

633 self.type_printers[cls] = printer 

634 return True 

635 return False 

636 

637 

638class PlainTextFormatter(BaseFormatter): 

639 """The default pretty-printer. 

640 

641 This uses :mod:`IPython.lib.pretty` to compute the format data of 

642 the object. If the object cannot be pretty printed, :func:`repr` is used. 

643 See the documentation of :mod:`IPython.lib.pretty` for details on 

644 how to write pretty printers. Here is a simple example:: 

645 

646 def dtype_pprinter(obj, p, cycle): 

647 if cycle: 

648 return p.text('dtype(...)') 

649 if hasattr(obj, 'fields'): 

650 if obj.fields is None: 

651 p.text(repr(obj)) 

652 else: 

653 p.begin_group(7, 'dtype([') 

654 for i, field in enumerate(obj.descr): 

655 if i > 0: 

656 p.text(',') 

657 p.breakable() 

658 p.pretty(field) 

659 p.end_group(7, '])') 

660 """ 

661 

662 # The format type of data returned. 

663 format_type = Unicode('text/plain') 

664 

665 # This subclass ignores this attribute as it always need to return 

666 # something. 

667 enabled = Bool(True).tag(config=False) 

668 

669 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, 

670 help="""Truncate large collections (lists, dicts, tuples, sets) to this size. 

671 

672 Set to 0 to disable truncation. 

673 """, 

674 ).tag(config=True) 

675 

676 # Look for a _repr_pretty_ methods to use for pretty printing. 

677 print_method = ObjectName('_repr_pretty_') 

678 

679 # Whether to pretty-print or not. 

680 pprint = Bool(True).tag(config=True) 

681 

682 # Whether to be verbose or not. 

683 verbose = Bool(False).tag(config=True) 

684 

685 # The maximum width. 

686 max_width = Integer(79).tag(config=True) 

687 

688 # The newline character. 

689 newline = Unicode('\n').tag(config=True) 

690 

691 # format-string for pprinting floats 

692 float_format = Unicode('%r') 

693 # setter for float precision, either int or direct format-string 

694 float_precision = CUnicode('').tag(config=True) 

695 

696 @observe('float_precision') 

697 def _float_precision_changed(self, change): 

698 """float_precision changed, set float_format accordingly. 

699 

700 float_precision can be set by int or str. 

701 This will set float_format, after interpreting input. 

702 If numpy has been imported, numpy print precision will also be set. 

703 

704 integer `n` sets format to '%.nf', otherwise, format set directly. 

705 

706 An empty string returns to defaults (repr for float, 8 for numpy). 

707 

708 This parameter can be set via the '%precision' magic. 

709 """ 

710 new = change['new'] 

711 if '%' in new: 

712 # got explicit format string 

713 fmt = new 

714 try: 

715 fmt%3.14159 

716 except Exception as e: 

717 raise ValueError("Precision must be int or format string, not %r"%new) from e 

718 elif new: 

719 # otherwise, should be an int 

720 try: 

721 i = int(new) 

722 assert i >= 0 

723 except ValueError as e: 

724 raise ValueError("Precision must be int or format string, not %r"%new) from e 

725 except AssertionError as e: 

726 raise ValueError("int precision must be non-negative, not %r"%i) from e 

727 

728 fmt = '%%.%if'%i 

729 if 'numpy' in sys.modules: 

730 # set numpy precision if it has been imported 

731 import numpy 

732 numpy.set_printoptions(precision=i) 

733 else: 

734 # default back to repr 

735 fmt = '%r' 

736 if 'numpy' in sys.modules: 

737 import numpy 

738 # numpy default is 8 

739 numpy.set_printoptions(precision=8) 

740 self.float_format = fmt 

741 

742 # Use the default pretty printers from IPython.lib.pretty. 

743 @default('singleton_printers') 

744 def _singleton_printers_default(self): 

745 return pretty._singleton_pprinters.copy() 

746 

747 @default('type_printers') 

748 def _type_printers_default(self): 

749 d = pretty._type_pprinters.copy() 

750 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) 

751 # if NumPy is used, set precision for its float64 type 

752 if "numpy" in sys.modules: 

753 import numpy 

754 

755 d[numpy.float64] = lambda obj, p, cycle: p.text(self.float_format % obj) 

756 return d 

757 

758 @default('deferred_printers') 

759 def _deferred_printers_default(self): 

760 return pretty._deferred_type_pprinters.copy() 

761 

762 #### FormatterABC interface #### 

763 

764 @catch_format_error 

765 def __call__(self, obj): 

766 """Compute the pretty representation of the object.""" 

767 if not self.pprint: 

768 return repr(obj) 

769 else: 

770 stream = StringIO() 

771 printer = pretty.RepresentationPrinter(stream, self.verbose, 

772 self.max_width, self.newline, 

773 max_seq_length=self.max_seq_length, 

774 singleton_pprinters=self.singleton_printers, 

775 type_pprinters=self.type_printers, 

776 deferred_pprinters=self.deferred_printers) 

777 printer.pretty(obj) 

778 printer.flush() 

779 return stream.getvalue() 

780 

781 

782class HTMLFormatter(BaseFormatter): 

783 """An HTML formatter. 

784 

785 To define the callables that compute the HTML representation of your 

786 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` 

787 or :meth:`for_type_by_name` methods to register functions that handle 

788 this. 

789 

790 The return value of this formatter should be a valid HTML snippet that 

791 could be injected into an existing DOM. It should *not* include the 

792 ```<html>`` or ```<body>`` tags. 

793 """ 

794 format_type = Unicode('text/html') 

795 

796 print_method = ObjectName('_repr_html_') 

797 

798 

799class MarkdownFormatter(BaseFormatter): 

800 """A Markdown formatter. 

801 

802 To define the callables that compute the Markdown representation of your 

803 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` 

804 or :meth:`for_type_by_name` methods to register functions that handle 

805 this. 

806 

807 The return value of this formatter should be a valid Markdown. 

808 """ 

809 format_type = Unicode('text/markdown') 

810 

811 print_method = ObjectName('_repr_markdown_') 

812 

813class SVGFormatter(BaseFormatter): 

814 """An SVG formatter. 

815 

816 To define the callables that compute the SVG representation of your 

817 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` 

818 or :meth:`for_type_by_name` methods to register functions that handle 

819 this. 

820 

821 The return value of this formatter should be valid SVG enclosed in 

822 ```<svg>``` tags, that could be injected into an existing DOM. It should 

823 *not* include the ```<html>`` or ```<body>`` tags. 

824 """ 

825 format_type = Unicode('image/svg+xml') 

826 

827 print_method = ObjectName('_repr_svg_') 

828 

829 

830class PNGFormatter(BaseFormatter): 

831 """A PNG formatter. 

832 

833 To define the callables that compute the PNG representation of your 

834 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` 

835 or :meth:`for_type_by_name` methods to register functions that handle 

836 this. 

837 

838 The return value of this formatter should be raw PNG data, *not* 

839 base64 encoded. 

840 """ 

841 format_type = Unicode('image/png') 

842 

843 print_method = ObjectName('_repr_png_') 

844 

845 _return_type = (bytes, str) 

846 

847 

848class JPEGFormatter(BaseFormatter): 

849 """A JPEG formatter. 

850 

851 To define the callables that compute the JPEG representation of your 

852 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` 

853 or :meth:`for_type_by_name` methods to register functions that handle 

854 this. 

855 

856 The return value of this formatter should be raw JPEG data, *not* 

857 base64 encoded. 

858 """ 

859 format_type = Unicode('image/jpeg') 

860 

861 print_method = ObjectName('_repr_jpeg_') 

862 

863 _return_type = (bytes, str) 

864 

865 

866class LatexFormatter(BaseFormatter): 

867 """A LaTeX formatter. 

868 

869 To define the callables that compute the LaTeX representation of your 

870 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` 

871 or :meth:`for_type_by_name` methods to register functions that handle 

872 this. 

873 

874 The return value of this formatter should be a valid LaTeX equation, 

875 enclosed in either ```$```, ```$$``` or another LaTeX equation 

876 environment. 

877 """ 

878 format_type = Unicode('text/latex') 

879 

880 print_method = ObjectName('_repr_latex_') 

881 

882 

883class JSONFormatter(BaseFormatter): 

884 """A JSON string formatter. 

885 

886 To define the callables that compute the JSONable representation of 

887 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` 

888 or :meth:`for_type_by_name` methods to register functions that handle 

889 this. 

890 

891 The return value of this formatter should be a JSONable list or dict. 

892 JSON scalars (None, number, string) are not allowed, only dict or list containers. 

893 """ 

894 format_type = Unicode('application/json') 

895 _return_type = (list, dict) 

896 

897 print_method = ObjectName('_repr_json_') 

898 

899 def _check_return(self, r, obj): 

900 """Check that a return value is appropriate 

901 

902 Return the value if so, None otherwise, warning if invalid. 

903 """ 

904 if r is None: 

905 return 

906 md = None 

907 if isinstance(r, tuple): 

908 # unpack data, metadata tuple for type checking on first element 

909 r, md = r 

910 

911 assert not isinstance( 

912 r, str 

913 ), "JSON-as-string has been deprecated since IPython < 3" 

914 

915 if md is not None: 

916 # put the tuple back together 

917 r = (r, md) 

918 return super()._check_return(r, obj) 

919 

920 

921class JavascriptFormatter(BaseFormatter): 

922 """A Javascript formatter. 

923 

924 To define the callables that compute the Javascript representation of 

925 your objects, define a :meth:`_repr_javascript_` method or use the 

926 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions 

927 that handle this. 

928 

929 The return value of this formatter should be valid Javascript code and 

930 should *not* be enclosed in ```<script>``` tags. 

931 """ 

932 format_type = Unicode('application/javascript') 

933 

934 print_method = ObjectName('_repr_javascript_') 

935 

936 

937class PDFFormatter(BaseFormatter): 

938 """A PDF formatter. 

939 

940 To define the callables that compute the PDF representation of your 

941 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` 

942 or :meth:`for_type_by_name` methods to register functions that handle 

943 this. 

944 

945 The return value of this formatter should be raw PDF data, *not* 

946 base64 encoded. 

947 """ 

948 format_type = Unicode('application/pdf') 

949 

950 print_method = ObjectName('_repr_pdf_') 

951 

952 _return_type = (bytes, str) 

953 

954class IPythonDisplayFormatter(BaseFormatter): 

955 """An escape-hatch Formatter for objects that know how to display themselves. 

956 

957 To define the callables that compute the representation of your 

958 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` 

959 or :meth:`for_type_by_name` methods to register functions that handle 

960 this. Unlike mime-type displays, this method should not return anything, 

961 instead calling any appropriate display methods itself. 

962 

963 This display formatter has highest priority. 

964 If it fires, no other display formatter will be called. 

965 

966 Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types 

967 without registering a new Formatter. 

968 

969 IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types, 

970 so `_ipython_display_` should only be used for objects that require unusual 

971 display patterns, such as multiple display calls. 

972 """ 

973 print_method = ObjectName('_ipython_display_') 

974 _return_type = (type(None), bool) 

975 

976 @catch_format_error 

977 def __call__(self, obj): 

978 """Compute the format for an object.""" 

979 if self.enabled: 

980 # lookup registered printer 

981 try: 

982 printer = self.lookup(obj) 

983 except KeyError: 

984 pass 

985 else: 

986 printer(obj) 

987 return True 

988 # Finally look for special method names 

989 method = get_real_method(obj, self.print_method) 

990 if method is not None: 

991 method() 

992 return True 

993 

994 

995class MimeBundleFormatter(BaseFormatter): 

996 """A Formatter for arbitrary mime-types. 

997 

998 Unlike other `_repr_<mimetype>_` methods, 

999 `_repr_mimebundle_` should return mime-bundle data, 

1000 either the mime-keyed `data` dictionary or the tuple `(data, metadata)`. 

1001 Any mime-type is valid. 

1002 

1003 To define the callables that compute the mime-bundle representation of your 

1004 objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type` 

1005 or :meth:`for_type_by_name` methods to register functions that handle 

1006 this. 

1007 

1008 .. versionadded:: 6.1 

1009 """ 

1010 print_method = ObjectName('_repr_mimebundle_') 

1011 _return_type = dict 

1012 

1013 def _check_return(self, r, obj): 

1014 r = super()._check_return(r, obj) 

1015 # always return (data, metadata): 

1016 if r is None: 

1017 return {}, {} 

1018 if not isinstance(r, tuple): 

1019 return r, {} 

1020 return r 

1021 

1022 @catch_format_error 

1023 def __call__(self, obj, include=None, exclude=None): 

1024 """Compute the format for an object. 

1025 

1026 Identical to parent's method but we pass extra parameters to the method. 

1027 

1028 Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in 

1029 particular `include` and `exclude`. 

1030 """ 

1031 if self.enabled: 

1032 # lookup registered printer 

1033 try: 

1034 printer = self.lookup(obj) 

1035 except KeyError: 

1036 pass 

1037 else: 

1038 return printer(obj) 

1039 # Finally look for special method names 

1040 method = get_real_method(obj, self.print_method) 

1041 

1042 if method is not None: 

1043 return method(include=include, exclude=exclude) 

1044 return None 

1045 else: 

1046 return None 

1047 

1048 

1049FormatterABC.register(BaseFormatter) 

1050FormatterABC.register(PlainTextFormatter) 

1051FormatterABC.register(HTMLFormatter) 

1052FormatterABC.register(MarkdownFormatter) 

1053FormatterABC.register(SVGFormatter) 

1054FormatterABC.register(PNGFormatter) 

1055FormatterABC.register(PDFFormatter) 

1056FormatterABC.register(JPEGFormatter) 

1057FormatterABC.register(LatexFormatter) 

1058FormatterABC.register(JSONFormatter) 

1059FormatterABC.register(JavascriptFormatter) 

1060FormatterABC.register(IPythonDisplayFormatter) 

1061FormatterABC.register(MimeBundleFormatter) 

1062 

1063 

1064def format_display_data(obj, include=None, exclude=None): 

1065 """Return a format data dict for an object. 

1066 

1067 By default all format types will be computed. 

1068 

1069 Parameters 

1070 ---------- 

1071 obj : object 

1072 The Python object whose format data will be computed. 

1073 

1074 Returns 

1075 ------- 

1076 format_dict : dict 

1077 A dictionary of key/value pairs, one or each format that was 

1078 generated for the object. The keys are the format types, which 

1079 will usually be MIME type strings and the values and JSON'able 

1080 data structure containing the raw data for the representation in 

1081 that format. 

1082 include : list or tuple, optional 

1083 A list of format type strings (MIME types) to include in the 

1084 format data dict. If this is set *only* the format types included 

1085 in this list will be computed. 

1086 exclude : list or tuple, optional 

1087 A list of format type string (MIME types) to exclude in the format 

1088 data dict. If this is set all format types will be computed, 

1089 except for those included in this argument. 

1090 """ 

1091 from .interactiveshell import InteractiveShell 

1092 

1093 return InteractiveShell.instance().display_formatter.format( 

1094 obj, 

1095 include, 

1096 exclude 

1097 )