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