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