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