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