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

361 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-26 06:07 +0000

1# -*- coding: utf-8 -*- 

2"""Display formatters. 

3 

4Inheritance diagram: 

5 

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

7 :parts: 3 

8""" 

9 

10# Copyright (c) IPython Development Team. 

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

12 

13import abc 

14import sys 

15import traceback 

16import warnings 

17from io import StringIO 

18 

19from decorator import decorator 

20 

21from traitlets.config.configurable import Configurable 

22from .getipython import get_ipython 

23from ..utils.sentinel import Sentinel 

24from ..utils.dir2 import get_real_method 

25from ..lib import pretty 

26from traitlets import ( 

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

28 ForwardDeclaredInstance, 

29 default, observe, 

30) 

31 

32 

33class DisplayFormatter(Configurable): 

34 

35 active_types = List(Unicode(), 

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

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

38  

39 Most users will not need to change this value. 

40 """).tag(config=True) 

41 

42 @default('active_types') 

43 def _active_types_default(self): 

44 return self.format_types 

45 

46 @observe('active_types') 

47 def _active_types_changed(self, change): 

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

49 if key in change['new']: 

50 formatter.enabled = True 

51 else: 

52 formatter.enabled = False 

53 

54 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') 

55 @default('ipython_display_formatter') 

56 def _default_formatter(self): 

57 return IPythonDisplayFormatter(parent=self) 

58 

59 mimebundle_formatter = ForwardDeclaredInstance('FormatterABC') 

60 @default('mimebundle_formatter') 

61 def _default_mime_formatter(self): 

62 return MimeBundleFormatter(parent=self) 

63 

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

65 # values are subclasses of BaseFormatter. 

66 formatters = Dict() 

67 @default('formatters') 

68 def _formatters_default(self): 

69 """Activate the default formatters.""" 

70 formatter_classes = [ 

71 PlainTextFormatter, 

72 HTMLFormatter, 

73 MarkdownFormatter, 

74 SVGFormatter, 

75 PNGFormatter, 

76 PDFFormatter, 

77 JPEGFormatter, 

78 LatexFormatter, 

79 JSONFormatter, 

80 JavascriptFormatter 

81 ] 

82 d = {} 

83 for cls in formatter_classes: 

84 f = cls(parent=self) 

85 d[f.format_type] = f 

86 return d 

87 

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

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

90 

91 By default all format types will be computed. 

92 

93 The following MIME types are usually implemented: 

94 

95 * text/plain 

96 * text/html 

97 * text/markdown 

98 * text/latex 

99 * application/json 

100 * application/javascript 

101 * application/pdf 

102 * image/png 

103 * image/jpeg 

104 * image/svg+xml 

105 

106 Parameters 

107 ---------- 

108 obj : object 

109 The Python object whose format data will be computed. 

110 include : list, tuple or set; optional 

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

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

113 in this list will be computed. 

114 exclude : list, tuple or set; optional 

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

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

117 except for those included in this argument. 

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

119 

120 Returns 

121 ------- 

122 (format_dict, metadata_dict) : tuple of two dicts 

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

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

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

126 data structure containing the raw data for the representation in 

127 that format. 

128 

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

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

131 

132 Notes 

133 ----- 

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

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

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

137 not be called. 

138 

139 """ 

140 format_dict = {} 

141 md_dict = {} 

142 

143 if self.ipython_display_formatter(obj): 

144 # object handled itself, don't proceed 

145 return {}, {} 

146 

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

148 

149 if format_dict or md_dict: 

150 if include: 

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

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

153 if exclude: 

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

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

156 

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

158 if format_type in format_dict: 

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

160 # exception: manually registered per-mime renderer 

161 # check priority: 

162 # 1. user-registered per-mime formatter 

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

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

165 try: 

166 formatter.lookup(obj) 

167 except KeyError: 

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

169 continue 

170 if include and format_type not in include: 

171 continue 

172 if exclude and format_type in exclude: 

173 continue 

174 

175 md = None 

176 try: 

177 data = formatter(obj) 

178 except: 

179 # FIXME: log the exception 

180 raise 

181 

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

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

184 data, md = data 

185 

186 if data is not None: 

187 format_dict[format_type] = data 

188 if md is not None: 

189 md_dict[format_type] = md 

190 return format_dict, md_dict 

191 

192 @property 

193 def format_types(self): 

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

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

196 

197 

198#----------------------------------------------------------------------------- 

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

200#----------------------------------------------------------------------------- 

201 

202 

203def _safe_repr(obj): 

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

205 

206 always returns a string, at least. 

207 """ 

208 try: 

209 return repr(obj) 

210 except Exception as e: 

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

212 

213 

214class FormatterWarning(UserWarning): 

215 """Warning class for errors in formatters""" 

216 

217@decorator 

218def catch_format_error(method, self, *args, **kwargs): 

219 """show traceback on failed format call""" 

220 try: 

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

222 except NotImplementedError: 

223 # don't warn on NotImplementedErrors 

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

225 except Exception: 

226 exc_info = sys.exc_info() 

227 ip = get_ipython() 

228 if ip is not None: 

229 ip.showtraceback(exc_info) 

230 else: 

231 traceback.print_exception(*exc_info) 

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

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

234 

235 

236class FormatterABC(metaclass=abc.ABCMeta): 

237 """ Abstract base class for Formatters. 

238 

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

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

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

242 the HTML representation of the object when called. 

243 """ 

244 

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

246 format_type = 'text/plain' 

247 

248 # Is the formatter enabled... 

249 enabled = True 

250 

251 @abc.abstractmethod 

252 def __call__(self, obj): 

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

254 

255 If the object cannot be formatted by this formatter, 

256 warn and return None. 

257 """ 

258 return repr(obj) 

259 

260 

261def _mod_name_key(typ): 

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

263 

264 Used as key in Formatter.deferred_printers. 

265 """ 

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

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

268 return (module, name) 

269 

270 

271def _get_type(obj): 

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

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

274 

275 

276_raise_key_error = Sentinel('_raise_key_error', __name__, 

277""" 

278Special value to raise a KeyError 

279 

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

281""") 

282 

283 

284class BaseFormatter(Configurable): 

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

286 

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

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

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

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

291 

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

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

294 for formatting. 

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

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

297 and :attr:`deferred_printers`. 

298 

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

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

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

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

303 methods. 

304 

305 If no function/callable is found to compute the format data, ``None`` is 

306 returned and this format type is not used. 

307 """ 

308 

309 format_type = Unicode('text/plain') 

310 _return_type = str 

311 

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

313 

314 print_method = ObjectName('__repr__') 

315 

316 # The singleton printers. 

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

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

319 

320 # The type-specific printers. 

321 # Map type objects to the format functions. 

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

323 

324 # The deferred-import type-specific printers. 

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

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

327 

328 @catch_format_error 

329 def __call__(self, obj): 

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

331 if self.enabled: 

332 # lookup registered printer 

333 try: 

334 printer = self.lookup(obj) 

335 except KeyError: 

336 pass 

337 else: 

338 return printer(obj) 

339 # Finally look for special method names 

340 method = get_real_method(obj, self.print_method) 

341 if method is not None: 

342 return method() 

343 return None 

344 else: 

345 return None 

346 

347 def __contains__(self, typ): 

348 """map in to lookup_by_type""" 

349 try: 

350 self.lookup_by_type(typ) 

351 except KeyError: 

352 return False 

353 else: 

354 return True 

355 

356 def _check_return(self, r, obj): 

357 """Check that a return value is appropriate 

358 

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

360 """ 

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

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

363 return r 

364 else: 

365 warnings.warn( 

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

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

368 FormatterWarning 

369 ) 

370 

371 def lookup(self, obj): 

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

373 

374 Parameters 

375 ---------- 

376 obj : object instance 

377 

378 Returns 

379 ------- 

380 f : callable 

381 The registered formatting callable for the type. 

382 

383 Raises 

384 ------ 

385 KeyError if the type has not been registered. 

386 """ 

387 # look for singleton first 

388 obj_id = id(obj) 

389 if obj_id in self.singleton_printers: 

390 return self.singleton_printers[obj_id] 

391 # then lookup by type 

392 return self.lookup_by_type(_get_type(obj)) 

393 

394 def lookup_by_type(self, typ): 

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

396 

397 Parameters 

398 ---------- 

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

400 

401 Returns 

402 ------- 

403 f : callable 

404 The registered formatting callable for the type. 

405 

406 Raises 

407 ------ 

408 KeyError if the type has not been registered. 

409 """ 

410 if isinstance(typ, str): 

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

412 if typ_key not in self.deferred_printers: 

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

414 # iterate over all of the types to check. 

415 for cls in self.type_printers: 

416 if _mod_name_key(cls) == typ_key: 

417 return self.type_printers[cls] 

418 else: 

419 return self.deferred_printers[typ_key] 

420 else: 

421 for cls in pretty._get_mro(typ): 

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

423 return self.type_printers[cls] 

424 

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

426 raise KeyError("No registered printer for {0!r}".format(typ)) 

427 

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

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

430 

431 Parameters 

432 ---------- 

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

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

435 

436 func : callable 

437 A callable for computing the format data. 

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

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

440 Subclasses may use a different call signature for the 

441 `func` argument. 

442 

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

444 only returning the current value. 

445 

446 Returns 

447 ------- 

448 oldfunc : callable 

449 The currently registered callable. 

450 If you are registering a new formatter, 

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

452 """ 

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

454 if isinstance(typ, str): 

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

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

457 

458 try: 

459 oldfunc = self.lookup_by_type(typ) 

460 except KeyError: 

461 oldfunc = None 

462 

463 if func is not None: 

464 self.type_printers[typ] = func 

465 

466 return oldfunc 

467 

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

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

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

471 

472 Parameters 

473 ---------- 

474 type_module : str 

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

476 ``numpy``. 

477 

478 type_name : str 

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

480 

481 func : callable 

482 A callable for computing the format data. 

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

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

485 Subclasses may use a different call signature for the 

486 `func` argument. 

487 

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

489 only returning the current value. 

490 

491 Returns 

492 ------- 

493 oldfunc : callable 

494 The currently registered callable. 

495 If you are registering a new formatter, 

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

497 """ 

498 key = (type_module, type_name) 

499 

500 try: 

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

502 except KeyError: 

503 oldfunc = None 

504 

505 if func is not None: 

506 self.deferred_printers[key] = func 

507 return oldfunc 

508 

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

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

511 

512 Parameters 

513 ---------- 

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

515 default : object 

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

517 

518 Returns 

519 ------- 

520 obj : object 

521 The last registered object for the type. 

522 

523 Raises 

524 ------ 

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

526 """ 

527 

528 if isinstance(typ, str): 

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

530 if typ_key not in self.deferred_printers: 

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

532 # iterate over all of the types to check. 

533 for cls in self.type_printers: 

534 if _mod_name_key(cls) == typ_key: 

535 old = self.type_printers.pop(cls) 

536 break 

537 else: 

538 old = default 

539 else: 

540 old = self.deferred_printers.pop(typ_key) 

541 else: 

542 if typ in self.type_printers: 

543 old = self.type_printers.pop(typ) 

544 else: 

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

546 if old is _raise_key_error: 

547 raise KeyError("No registered value for {0!r}".format(typ)) 

548 return old 

549 

550 def _in_deferred_types(self, cls): 

551 """ 

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

553 

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

555 """ 

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

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

558 key = (mod, name) 

559 if key in self.deferred_printers: 

560 # Move the printer over to the regular registry. 

561 printer = self.deferred_printers.pop(key) 

562 self.type_printers[cls] = printer 

563 return True 

564 return False 

565 

566 

567class PlainTextFormatter(BaseFormatter): 

568 """The default pretty-printer. 

569 

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

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

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

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

574 

575 def dtype_pprinter(obj, p, cycle): 

576 if cycle: 

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

578 if hasattr(obj, 'fields'): 

579 if obj.fields is None: 

580 p.text(repr(obj)) 

581 else: 

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

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

584 if i > 0: 

585 p.text(',') 

586 p.breakable() 

587 p.pretty(field) 

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

589 """ 

590 

591 # The format type of data returned. 

592 format_type = Unicode('text/plain') 

593 

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

595 # something. 

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

597 

598 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, 

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

600  

601 Set to 0 to disable truncation. 

602 """ 

603 ).tag(config=True) 

604 

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

606 print_method = ObjectName('_repr_pretty_') 

607 

608 # Whether to pretty-print or not. 

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

610 

611 # Whether to be verbose or not. 

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

613 

614 # The maximum width. 

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

616 

617 # The newline character. 

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

619 

620 # format-string for pprinting floats 

621 float_format = Unicode('%r') 

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

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

624 

625 @observe('float_precision') 

626 def _float_precision_changed(self, change): 

627 """float_precision changed, set float_format accordingly. 

628 

629 float_precision can be set by int or str. 

630 This will set float_format, after interpreting input. 

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

632 

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

634 

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

636 

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

638 """ 

639 new = change['new'] 

640 if '%' in new: 

641 # got explicit format string 

642 fmt = new 

643 try: 

644 fmt%3.14159 

645 except Exception as e: 

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

647 elif new: 

648 # otherwise, should be an int 

649 try: 

650 i = int(new) 

651 assert i >= 0 

652 except ValueError as e: 

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

654 except AssertionError as e: 

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

656 

657 fmt = '%%.%if'%i 

658 if 'numpy' in sys.modules: 

659 # set numpy precision if it has been imported 

660 import numpy 

661 numpy.set_printoptions(precision=i) 

662 else: 

663 # default back to repr 

664 fmt = '%r' 

665 if 'numpy' in sys.modules: 

666 import numpy 

667 # numpy default is 8 

668 numpy.set_printoptions(precision=8) 

669 self.float_format = fmt 

670 

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

672 @default('singleton_printers') 

673 def _singleton_printers_default(self): 

674 return pretty._singleton_pprinters.copy() 

675 

676 @default('type_printers') 

677 def _type_printers_default(self): 

678 d = pretty._type_pprinters.copy() 

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

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

681 if "numpy" in sys.modules: 

682 import numpy 

683 

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

685 return d 

686 

687 @default('deferred_printers') 

688 def _deferred_printers_default(self): 

689 return pretty._deferred_type_pprinters.copy() 

690 

691 #### FormatterABC interface #### 

692 

693 @catch_format_error 

694 def __call__(self, obj): 

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

696 if not self.pprint: 

697 return repr(obj) 

698 else: 

699 stream = StringIO() 

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

701 self.max_width, self.newline, 

702 max_seq_length=self.max_seq_length, 

703 singleton_pprinters=self.singleton_printers, 

704 type_pprinters=self.type_printers, 

705 deferred_pprinters=self.deferred_printers) 

706 printer.pretty(obj) 

707 printer.flush() 

708 return stream.getvalue() 

709 

710 

711class HTMLFormatter(BaseFormatter): 

712 """An HTML formatter. 

713 

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

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

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

717 this. 

718 

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

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

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

722 """ 

723 format_type = Unicode('text/html') 

724 

725 print_method = ObjectName('_repr_html_') 

726 

727 

728class MarkdownFormatter(BaseFormatter): 

729 """A Markdown formatter. 

730 

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

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

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

734 this. 

735 

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

737 """ 

738 format_type = Unicode('text/markdown') 

739 

740 print_method = ObjectName('_repr_markdown_') 

741 

742class SVGFormatter(BaseFormatter): 

743 """An SVG formatter. 

744 

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

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

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

748 this. 

749 

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

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

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

753 """ 

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

755 

756 print_method = ObjectName('_repr_svg_') 

757 

758 

759class PNGFormatter(BaseFormatter): 

760 """A PNG formatter. 

761 

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

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

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

765 this. 

766 

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

768 base64 encoded. 

769 """ 

770 format_type = Unicode('image/png') 

771 

772 print_method = ObjectName('_repr_png_') 

773 

774 _return_type = (bytes, str) 

775 

776 

777class JPEGFormatter(BaseFormatter): 

778 """A JPEG formatter. 

779 

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

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

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

783 this. 

784 

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

786 base64 encoded. 

787 """ 

788 format_type = Unicode('image/jpeg') 

789 

790 print_method = ObjectName('_repr_jpeg_') 

791 

792 _return_type = (bytes, str) 

793 

794 

795class LatexFormatter(BaseFormatter): 

796 """A LaTeX formatter. 

797 

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

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

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

801 this. 

802 

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

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

805 environment. 

806 """ 

807 format_type = Unicode('text/latex') 

808 

809 print_method = ObjectName('_repr_latex_') 

810 

811 

812class JSONFormatter(BaseFormatter): 

813 """A JSON string formatter. 

814 

815 To define the callables that compute the JSONable representation of 

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

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

818 this. 

819 

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

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

822 """ 

823 format_type = Unicode('application/json') 

824 _return_type = (list, dict) 

825 

826 print_method = ObjectName('_repr_json_') 

827 

828 def _check_return(self, r, obj): 

829 """Check that a return value is appropriate 

830 

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

832 """ 

833 if r is None: 

834 return 

835 md = None 

836 if isinstance(r, tuple): 

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

838 r, md = r 

839 

840 assert not isinstance( 

841 r, str 

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

843 

844 if md is not None: 

845 # put the tuple back together 

846 r = (r, md) 

847 return super(JSONFormatter, self)._check_return(r, obj) 

848 

849 

850class JavascriptFormatter(BaseFormatter): 

851 """A Javascript formatter. 

852 

853 To define the callables that compute the Javascript representation of 

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

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

856 that handle this. 

857 

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

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

860 """ 

861 format_type = Unicode('application/javascript') 

862 

863 print_method = ObjectName('_repr_javascript_') 

864 

865 

866class PDFFormatter(BaseFormatter): 

867 """A PDF formatter. 

868 

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

870 objects, define a :meth:`_repr_pdf_` 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 raw PDF data, *not* 

875 base64 encoded. 

876 """ 

877 format_type = Unicode('application/pdf') 

878 

879 print_method = ObjectName('_repr_pdf_') 

880 

881 _return_type = (bytes, str) 

882 

883class IPythonDisplayFormatter(BaseFormatter): 

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

885  

886 To define the callables that compute the representation of your 

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

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

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

890 instead calling any appropriate display methods itself. 

891  

892 This display formatter has highest priority. 

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

894 

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

896 without registering a new Formatter. 

897  

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

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

900 display patterns, such as multiple display calls. 

901 """ 

902 print_method = ObjectName('_ipython_display_') 

903 _return_type = (type(None), bool) 

904 

905 @catch_format_error 

906 def __call__(self, obj): 

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

908 if self.enabled: 

909 # lookup registered printer 

910 try: 

911 printer = self.lookup(obj) 

912 except KeyError: 

913 pass 

914 else: 

915 printer(obj) 

916 return True 

917 # Finally look for special method names 

918 method = get_real_method(obj, self.print_method) 

919 if method is not None: 

920 method() 

921 return True 

922 

923 

924class MimeBundleFormatter(BaseFormatter): 

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

926 

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

928 `_repr_mimebundle_` should return mime-bundle data, 

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

930 Any mime-type is valid. 

931 

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

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

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

935 this. 

936 

937 .. versionadded:: 6.1 

938 """ 

939 print_method = ObjectName('_repr_mimebundle_') 

940 _return_type = dict 

941 

942 def _check_return(self, r, obj): 

943 r = super(MimeBundleFormatter, self)._check_return(r, obj) 

944 # always return (data, metadata): 

945 if r is None: 

946 return {}, {} 

947 if not isinstance(r, tuple): 

948 return r, {} 

949 return r 

950 

951 @catch_format_error 

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

953 """Compute the format for an object. 

954 

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

956 

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

958 particular `include` and `exclude`. 

959 """ 

960 if self.enabled: 

961 # lookup registered printer 

962 try: 

963 printer = self.lookup(obj) 

964 except KeyError: 

965 pass 

966 else: 

967 return printer(obj) 

968 # Finally look for special method names 

969 method = get_real_method(obj, self.print_method) 

970 

971 if method is not None: 

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

973 return None 

974 else: 

975 return None 

976 

977 

978FormatterABC.register(BaseFormatter) 

979FormatterABC.register(PlainTextFormatter) 

980FormatterABC.register(HTMLFormatter) 

981FormatterABC.register(MarkdownFormatter) 

982FormatterABC.register(SVGFormatter) 

983FormatterABC.register(PNGFormatter) 

984FormatterABC.register(PDFFormatter) 

985FormatterABC.register(JPEGFormatter) 

986FormatterABC.register(LatexFormatter) 

987FormatterABC.register(JSONFormatter) 

988FormatterABC.register(JavascriptFormatter) 

989FormatterABC.register(IPythonDisplayFormatter) 

990FormatterABC.register(MimeBundleFormatter) 

991 

992 

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

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

995 

996 By default all format types will be computed. 

997 

998 Parameters 

999 ---------- 

1000 obj : object 

1001 The Python object whose format data will be computed. 

1002 

1003 Returns 

1004 ------- 

1005 format_dict : dict 

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

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

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

1009 data structure containing the raw data for the representation in 

1010 that format. 

1011 include : list or tuple, optional 

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

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

1014 in this list will be computed. 

1015 exclude : list or tuple, optional 

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

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

1018 except for those included in this argument. 

1019 """ 

1020 from .interactiveshell import InteractiveShell 

1021 

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

1023 obj, 

1024 include, 

1025 exclude 

1026 )