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