##// END OF EJS Templates
Merge pull request #10142 from srinivasreddy/CUnicodeIO...
Thomas Kluyver -
r23127:b7a7f0b0 merge
parent child Browse files
Show More
@@ -1,944 +1,941 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4 Inheritance diagram:
4 Inheritance diagram:
5
5
6 .. inheritance-diagram:: IPython.core.formatters
6 .. inheritance-diagram:: IPython.core.formatters
7 :parts: 3
7 :parts: 3
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12
12
13 import abc
13 import abc
14 import json
14 import json
15 import sys
15 import sys
16 import traceback
16 import traceback
17 import warnings
17 import warnings
18 from io import StringIO
18
19
19 from decorator import decorator
20 from decorator import decorator
20
21
21 from traitlets.config.configurable import Configurable
22 from traitlets.config.configurable import Configurable
22 from IPython.core.getipython import get_ipython
23 from IPython.core.getipython import get_ipython
23 from IPython.utils.sentinel import Sentinel
24 from IPython.utils.sentinel import Sentinel
24 from IPython.utils.dir2 import get_real_method
25 from IPython.utils.dir2 import get_real_method
25 from IPython.lib import pretty
26 from IPython.lib import pretty
26 from traitlets import (
27 from traitlets import (
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 ForwardDeclaredInstance,
29 ForwardDeclaredInstance,
29 default, observe,
30 default, observe,
30 )
31 )
31
32
32
33
33 class DisplayFormatter(Configurable):
34 class DisplayFormatter(Configurable):
34
35
35 active_types = List(Unicode(),
36 active_types = List(Unicode(),
36 help="""List of currently active mime-types to display.
37 help="""List of currently active mime-types to display.
37 You can use this to set a white-list for formats to display.
38 You can use this to set a white-list for formats to display.
38
39
39 Most users will not need to change this value.
40 Most users will not need to change this value.
40 """).tag(config=True)
41 """).tag(config=True)
41
42
42 @default('active_types')
43 @default('active_types')
43 def _active_types_default(self):
44 def _active_types_default(self):
44 return self.format_types
45 return self.format_types
45
46
46 @observe('active_types')
47 @observe('active_types')
47 def _active_types_changed(self, change):
48 def _active_types_changed(self, change):
48 for key, formatter in self.formatters.items():
49 for key, formatter in self.formatters.items():
49 if key in change['new']:
50 if key in change['new']:
50 formatter.enabled = True
51 formatter.enabled = True
51 else:
52 else:
52 formatter.enabled = False
53 formatter.enabled = False
53
54
54 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
55 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
55 @default('ipython_display_formatter')
56 @default('ipython_display_formatter')
56 def _default_formatter(self):
57 def _default_formatter(self):
57 return IPythonDisplayFormatter(parent=self)
58 return IPythonDisplayFormatter(parent=self)
58
59
59 # A dict of formatter whose keys are format types (MIME types) and whose
60 # A dict of formatter whose keys are format types (MIME types) and whose
60 # values are subclasses of BaseFormatter.
61 # values are subclasses of BaseFormatter.
61 formatters = Dict()
62 formatters = Dict()
62 @default('formatters')
63 @default('formatters')
63 def _formatters_default(self):
64 def _formatters_default(self):
64 """Activate the default formatters."""
65 """Activate the default formatters."""
65 formatter_classes = [
66 formatter_classes = [
66 PlainTextFormatter,
67 PlainTextFormatter,
67 HTMLFormatter,
68 HTMLFormatter,
68 MarkdownFormatter,
69 MarkdownFormatter,
69 SVGFormatter,
70 SVGFormatter,
70 PNGFormatter,
71 PNGFormatter,
71 PDFFormatter,
72 PDFFormatter,
72 JPEGFormatter,
73 JPEGFormatter,
73 LatexFormatter,
74 LatexFormatter,
74 JSONFormatter,
75 JSONFormatter,
75 JavascriptFormatter
76 JavascriptFormatter
76 ]
77 ]
77 d = {}
78 d = {}
78 for cls in formatter_classes:
79 for cls in formatter_classes:
79 f = cls(parent=self)
80 f = cls(parent=self)
80 d[f.format_type] = f
81 d[f.format_type] = f
81 return d
82 return d
82
83
83 def format(self, obj, include=None, exclude=None):
84 def format(self, obj, include=None, exclude=None):
84 """Return a format data dict for an object.
85 """Return a format data dict for an object.
85
86
86 By default all format types will be computed.
87 By default all format types will be computed.
87
88
88 The following MIME types are currently implemented:
89 The following MIME types are currently implemented:
89
90
90 * text/plain
91 * text/plain
91 * text/html
92 * text/html
92 * text/markdown
93 * text/markdown
93 * text/latex
94 * text/latex
94 * application/json
95 * application/json
95 * application/javascript
96 * application/javascript
96 * application/pdf
97 * application/pdf
97 * image/png
98 * image/png
98 * image/jpeg
99 * image/jpeg
99 * image/svg+xml
100 * image/svg+xml
100
101
101 Parameters
102 Parameters
102 ----------
103 ----------
103 obj : object
104 obj : object
104 The Python object whose format data will be computed.
105 The Python object whose format data will be computed.
105 include : list or tuple, optional
106 include : list or tuple, optional
106 A list of format type strings (MIME types) to include in the
107 A list of format type strings (MIME types) to include in the
107 format data dict. If this is set *only* the format types included
108 format data dict. If this is set *only* the format types included
108 in this list will be computed.
109 in this list will be computed.
109 exclude : list or tuple, optional
110 exclude : list or tuple, optional
110 A list of format type string (MIME types) to exclude in the format
111 A list of format type string (MIME types) to exclude in the format
111 data dict. If this is set all format types will be computed,
112 data dict. If this is set all format types will be computed,
112 except for those included in this argument.
113 except for those included in this argument.
113
114
114 Returns
115 Returns
115 -------
116 -------
116 (format_dict, metadata_dict) : tuple of two dicts
117 (format_dict, metadata_dict) : tuple of two dicts
117
118
118 format_dict is a dictionary of key/value pairs, one of each format that was
119 format_dict is a dictionary of key/value pairs, one of each format that was
119 generated for the object. The keys are the format types, which
120 generated for the object. The keys are the format types, which
120 will usually be MIME type strings and the values and JSON'able
121 will usually be MIME type strings and the values and JSON'able
121 data structure containing the raw data for the representation in
122 data structure containing the raw data for the representation in
122 that format.
123 that format.
123
124
124 metadata_dict is a dictionary of metadata about each mime-type output.
125 metadata_dict is a dictionary of metadata about each mime-type output.
125 Its keys will be a strict subset of the keys in format_dict.
126 Its keys will be a strict subset of the keys in format_dict.
126 """
127 """
127 format_dict = {}
128 format_dict = {}
128 md_dict = {}
129 md_dict = {}
129
130
130 if self.ipython_display_formatter(obj):
131 if self.ipython_display_formatter(obj):
131 # object handled itself, don't proceed
132 # object handled itself, don't proceed
132 return {}, {}
133 return {}, {}
133
134
134 for format_type, formatter in self.formatters.items():
135 for format_type, formatter in self.formatters.items():
135 if include and format_type not in include:
136 if include and format_type not in include:
136 continue
137 continue
137 if exclude and format_type in exclude:
138 if exclude and format_type in exclude:
138 continue
139 continue
139
140
140 md = None
141 md = None
141 try:
142 try:
142 data = formatter(obj)
143 data = formatter(obj)
143 except:
144 except:
144 # FIXME: log the exception
145 # FIXME: log the exception
145 raise
146 raise
146
147
147 # formatters can return raw data or (data, metadata)
148 # formatters can return raw data or (data, metadata)
148 if isinstance(data, tuple) and len(data) == 2:
149 if isinstance(data, tuple) and len(data) == 2:
149 data, md = data
150 data, md = data
150
151
151 if data is not None:
152 if data is not None:
152 format_dict[format_type] = data
153 format_dict[format_type] = data
153 if md is not None:
154 if md is not None:
154 md_dict[format_type] = md
155 md_dict[format_type] = md
155
156
156 return format_dict, md_dict
157 return format_dict, md_dict
157
158
158 @property
159 @property
159 def format_types(self):
160 def format_types(self):
160 """Return the format types (MIME types) of the active formatters."""
161 """Return the format types (MIME types) of the active formatters."""
161 return list(self.formatters.keys())
162 return list(self.formatters.keys())
162
163
163
164
164 #-----------------------------------------------------------------------------
165 #-----------------------------------------------------------------------------
165 # Formatters for specific format types (text, html, svg, etc.)
166 # Formatters for specific format types (text, html, svg, etc.)
166 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
167
168
168
169
169 def _safe_repr(obj):
170 def _safe_repr(obj):
170 """Try to return a repr of an object
171 """Try to return a repr of an object
171
172
172 always returns a string, at least.
173 always returns a string, at least.
173 """
174 """
174 try:
175 try:
175 return repr(obj)
176 return repr(obj)
176 except Exception as e:
177 except Exception as e:
177 return "un-repr-able object (%r)" % e
178 return "un-repr-able object (%r)" % e
178
179
179
180
180 class FormatterWarning(UserWarning):
181 class FormatterWarning(UserWarning):
181 """Warning class for errors in formatters"""
182 """Warning class for errors in formatters"""
182
183
183 @decorator
184 @decorator
184 def catch_format_error(method, self, *args, **kwargs):
185 def catch_format_error(method, self, *args, **kwargs):
185 """show traceback on failed format call"""
186 """show traceback on failed format call"""
186 try:
187 try:
187 r = method(self, *args, **kwargs)
188 r = method(self, *args, **kwargs)
188 except NotImplementedError:
189 except NotImplementedError:
189 # don't warn on NotImplementedErrors
190 # don't warn on NotImplementedErrors
190 return None
191 return None
191 except Exception:
192 except Exception:
192 exc_info = sys.exc_info()
193 exc_info = sys.exc_info()
193 ip = get_ipython()
194 ip = get_ipython()
194 if ip is not None:
195 if ip is not None:
195 ip.showtraceback(exc_info)
196 ip.showtraceback(exc_info)
196 else:
197 else:
197 traceback.print_exception(*exc_info)
198 traceback.print_exception(*exc_info)
198 return None
199 return None
199 return self._check_return(r, args[0])
200 return self._check_return(r, args[0])
200
201
201
202
202 class FormatterABC(metaclass=abc.ABCMeta):
203 class FormatterABC(metaclass=abc.ABCMeta):
203 """ Abstract base class for Formatters.
204 """ Abstract base class for Formatters.
204
205
205 A formatter is a callable class that is responsible for computing the
206 A formatter is a callable class that is responsible for computing the
206 raw format data for a particular format type (MIME type). For example,
207 raw format data for a particular format type (MIME type). For example,
207 an HTML formatter would have a format type of `text/html` and would return
208 an HTML formatter would have a format type of `text/html` and would return
208 the HTML representation of the object when called.
209 the HTML representation of the object when called.
209 """
210 """
210
211
211 # The format type of the data returned, usually a MIME type.
212 # The format type of the data returned, usually a MIME type.
212 format_type = 'text/plain'
213 format_type = 'text/plain'
213
214
214 # Is the formatter enabled...
215 # Is the formatter enabled...
215 enabled = True
216 enabled = True
216
217
217 @abc.abstractmethod
218 @abc.abstractmethod
218 def __call__(self, obj):
219 def __call__(self, obj):
219 """Return a JSON'able representation of the object.
220 """Return a JSON'able representation of the object.
220
221
221 If the object cannot be formatted by this formatter,
222 If the object cannot be formatted by this formatter,
222 warn and return None.
223 warn and return None.
223 """
224 """
224 return repr(obj)
225 return repr(obj)
225
226
226
227
227 def _mod_name_key(typ):
228 def _mod_name_key(typ):
228 """Return a (__module__, __name__) tuple for a type.
229 """Return a (__module__, __name__) tuple for a type.
229
230
230 Used as key in Formatter.deferred_printers.
231 Used as key in Formatter.deferred_printers.
231 """
232 """
232 module = getattr(typ, '__module__', None)
233 module = getattr(typ, '__module__', None)
233 name = getattr(typ, '__name__', None)
234 name = getattr(typ, '__name__', None)
234 return (module, name)
235 return (module, name)
235
236
236
237
237 def _get_type(obj):
238 def _get_type(obj):
238 """Return the type of an instance (old and new-style)"""
239 """Return the type of an instance (old and new-style)"""
239 return getattr(obj, '__class__', None) or type(obj)
240 return getattr(obj, '__class__', None) or type(obj)
240
241
241
242
242 _raise_key_error = Sentinel('_raise_key_error', __name__,
243 _raise_key_error = Sentinel('_raise_key_error', __name__,
243 """
244 """
244 Special value to raise a KeyError
245 Special value to raise a KeyError
245
246
246 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
247 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
247 """)
248 """)
248
249
249
250
250 class BaseFormatter(Configurable):
251 class BaseFormatter(Configurable):
251 """A base formatter class that is configurable.
252 """A base formatter class that is configurable.
252
253
253 This formatter should usually be used as the base class of all formatters.
254 This formatter should usually be used as the base class of all formatters.
254 It is a traited :class:`Configurable` class and includes an extensible
255 It is a traited :class:`Configurable` class and includes an extensible
255 API for users to determine how their objects are formatted. The following
256 API for users to determine how their objects are formatted. The following
256 logic is used to find a function to format an given object.
257 logic is used to find a function to format an given object.
257
258
258 1. The object is introspected to see if it has a method with the name
259 1. The object is introspected to see if it has a method with the name
259 :attr:`print_method`. If is does, that object is passed to that method
260 :attr:`print_method`. If is does, that object is passed to that method
260 for formatting.
261 for formatting.
261 2. If no print method is found, three internal dictionaries are consulted
262 2. If no print method is found, three internal dictionaries are consulted
262 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
263 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
263 and :attr:`deferred_printers`.
264 and :attr:`deferred_printers`.
264
265
265 Users should use these dictionaries to register functions that will be
266 Users should use these dictionaries to register functions that will be
266 used to compute the format data for their objects (if those objects don't
267 used to compute the format data for their objects (if those objects don't
267 have the special print methods). The easiest way of using these
268 have the special print methods). The easiest way of using these
268 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
269 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
269 methods.
270 methods.
270
271
271 If no function/callable is found to compute the format data, ``None`` is
272 If no function/callable is found to compute the format data, ``None`` is
272 returned and this format type is not used.
273 returned and this format type is not used.
273 """
274 """
274
275
275 format_type = Unicode('text/plain')
276 format_type = Unicode('text/plain')
276 _return_type = str
277 _return_type = str
277
278
278 enabled = Bool(True).tag(config=True)
279 enabled = Bool(True).tag(config=True)
279
280
280 print_method = ObjectName('__repr__')
281 print_method = ObjectName('__repr__')
281
282
282 # The singleton printers.
283 # The singleton printers.
283 # Maps the IDs of the builtin singleton objects to the format functions.
284 # Maps the IDs of the builtin singleton objects to the format functions.
284 singleton_printers = Dict().tag(config=True)
285 singleton_printers = Dict().tag(config=True)
285
286
286 # The type-specific printers.
287 # The type-specific printers.
287 # Map type objects to the format functions.
288 # Map type objects to the format functions.
288 type_printers = Dict().tag(config=True)
289 type_printers = Dict().tag(config=True)
289
290
290 # The deferred-import type-specific printers.
291 # The deferred-import type-specific printers.
291 # Map (modulename, classname) pairs to the format functions.
292 # Map (modulename, classname) pairs to the format functions.
292 deferred_printers = Dict().tag(config=True)
293 deferred_printers = Dict().tag(config=True)
293
294
294 @catch_format_error
295 @catch_format_error
295 def __call__(self, obj):
296 def __call__(self, obj):
296 """Compute the format for an object."""
297 """Compute the format for an object."""
297 if self.enabled:
298 if self.enabled:
298 # lookup registered printer
299 # lookup registered printer
299 try:
300 try:
300 printer = self.lookup(obj)
301 printer = self.lookup(obj)
301 except KeyError:
302 except KeyError:
302 pass
303 pass
303 else:
304 else:
304 return printer(obj)
305 return printer(obj)
305 # Finally look for special method names
306 # Finally look for special method names
306 method = get_real_method(obj, self.print_method)
307 method = get_real_method(obj, self.print_method)
307 if method is not None:
308 if method is not None:
308 return method()
309 return method()
309 return None
310 return None
310 else:
311 else:
311 return None
312 return None
312
313
313 def __contains__(self, typ):
314 def __contains__(self, typ):
314 """map in to lookup_by_type"""
315 """map in to lookup_by_type"""
315 try:
316 try:
316 self.lookup_by_type(typ)
317 self.lookup_by_type(typ)
317 except KeyError:
318 except KeyError:
318 return False
319 return False
319 else:
320 else:
320 return True
321 return True
321
322
322 def _check_return(self, r, obj):
323 def _check_return(self, r, obj):
323 """Check that a return value is appropriate
324 """Check that a return value is appropriate
324
325
325 Return the value if so, None otherwise, warning if invalid.
326 Return the value if so, None otherwise, warning if invalid.
326 """
327 """
327 if r is None or isinstance(r, self._return_type) or \
328 if r is None or isinstance(r, self._return_type) or \
328 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
329 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
329 return r
330 return r
330 else:
331 else:
331 warnings.warn(
332 warnings.warn(
332 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
333 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
333 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
334 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
334 FormatterWarning
335 FormatterWarning
335 )
336 )
336
337
337 def lookup(self, obj):
338 def lookup(self, obj):
338 """Look up the formatter for a given instance.
339 """Look up the formatter for a given instance.
339
340
340 Parameters
341 Parameters
341 ----------
342 ----------
342 obj : object instance
343 obj : object instance
343
344
344 Returns
345 Returns
345 -------
346 -------
346 f : callable
347 f : callable
347 The registered formatting callable for the type.
348 The registered formatting callable for the type.
348
349
349 Raises
350 Raises
350 ------
351 ------
351 KeyError if the type has not been registered.
352 KeyError if the type has not been registered.
352 """
353 """
353 # look for singleton first
354 # look for singleton first
354 obj_id = id(obj)
355 obj_id = id(obj)
355 if obj_id in self.singleton_printers:
356 if obj_id in self.singleton_printers:
356 return self.singleton_printers[obj_id]
357 return self.singleton_printers[obj_id]
357 # then lookup by type
358 # then lookup by type
358 return self.lookup_by_type(_get_type(obj))
359 return self.lookup_by_type(_get_type(obj))
359
360
360 def lookup_by_type(self, typ):
361 def lookup_by_type(self, typ):
361 """Look up the registered formatter for a type.
362 """Look up the registered formatter for a type.
362
363
363 Parameters
364 Parameters
364 ----------
365 ----------
365 typ : type or '__module__.__name__' string for a type
366 typ : type or '__module__.__name__' string for a type
366
367
367 Returns
368 Returns
368 -------
369 -------
369 f : callable
370 f : callable
370 The registered formatting callable for the type.
371 The registered formatting callable for the type.
371
372
372 Raises
373 Raises
373 ------
374 ------
374 KeyError if the type has not been registered.
375 KeyError if the type has not been registered.
375 """
376 """
376 if isinstance(typ, str):
377 if isinstance(typ, str):
377 typ_key = tuple(typ.rsplit('.',1))
378 typ_key = tuple(typ.rsplit('.',1))
378 if typ_key not in self.deferred_printers:
379 if typ_key not in self.deferred_printers:
379 # We may have it cached in the type map. We will have to
380 # We may have it cached in the type map. We will have to
380 # iterate over all of the types to check.
381 # iterate over all of the types to check.
381 for cls in self.type_printers:
382 for cls in self.type_printers:
382 if _mod_name_key(cls) == typ_key:
383 if _mod_name_key(cls) == typ_key:
383 return self.type_printers[cls]
384 return self.type_printers[cls]
384 else:
385 else:
385 return self.deferred_printers[typ_key]
386 return self.deferred_printers[typ_key]
386 else:
387 else:
387 for cls in pretty._get_mro(typ):
388 for cls in pretty._get_mro(typ):
388 if cls in self.type_printers or self._in_deferred_types(cls):
389 if cls in self.type_printers or self._in_deferred_types(cls):
389 return self.type_printers[cls]
390 return self.type_printers[cls]
390
391
391 # If we have reached here, the lookup failed.
392 # If we have reached here, the lookup failed.
392 raise KeyError("No registered printer for {0!r}".format(typ))
393 raise KeyError("No registered printer for {0!r}".format(typ))
393
394
394 def for_type(self, typ, func=None):
395 def for_type(self, typ, func=None):
395 """Add a format function for a given type.
396 """Add a format function for a given type.
396
397
397 Parameters
398 Parameters
398 -----------
399 -----------
399 typ : type or '__module__.__name__' string for a type
400 typ : type or '__module__.__name__' string for a type
400 The class of the object that will be formatted using `func`.
401 The class of the object that will be formatted using `func`.
401 func : callable
402 func : callable
402 A callable for computing the format data.
403 A callable for computing the format data.
403 `func` will be called with the object to be formatted,
404 `func` will be called with the object to be formatted,
404 and will return the raw data in this formatter's format.
405 and will return the raw data in this formatter's format.
405 Subclasses may use a different call signature for the
406 Subclasses may use a different call signature for the
406 `func` argument.
407 `func` argument.
407
408
408 If `func` is None or not specified, there will be no change,
409 If `func` is None or not specified, there will be no change,
409 only returning the current value.
410 only returning the current value.
410
411
411 Returns
412 Returns
412 -------
413 -------
413 oldfunc : callable
414 oldfunc : callable
414 The currently registered callable.
415 The currently registered callable.
415 If you are registering a new formatter,
416 If you are registering a new formatter,
416 this will be the previous value (to enable restoring later).
417 this will be the previous value (to enable restoring later).
417 """
418 """
418 # if string given, interpret as 'pkg.module.class_name'
419 # if string given, interpret as 'pkg.module.class_name'
419 if isinstance(typ, str):
420 if isinstance(typ, str):
420 type_module, type_name = typ.rsplit('.', 1)
421 type_module, type_name = typ.rsplit('.', 1)
421 return self.for_type_by_name(type_module, type_name, func)
422 return self.for_type_by_name(type_module, type_name, func)
422
423
423 try:
424 try:
424 oldfunc = self.lookup_by_type(typ)
425 oldfunc = self.lookup_by_type(typ)
425 except KeyError:
426 except KeyError:
426 oldfunc = None
427 oldfunc = None
427
428
428 if func is not None:
429 if func is not None:
429 self.type_printers[typ] = func
430 self.type_printers[typ] = func
430
431
431 return oldfunc
432 return oldfunc
432
433
433 def for_type_by_name(self, type_module, type_name, func=None):
434 def for_type_by_name(self, type_module, type_name, func=None):
434 """Add a format function for a type specified by the full dotted
435 """Add a format function for a type specified by the full dotted
435 module and name of the type, rather than the type of the object.
436 module and name of the type, rather than the type of the object.
436
437
437 Parameters
438 Parameters
438 ----------
439 ----------
439 type_module : str
440 type_module : str
440 The full dotted name of the module the type is defined in, like
441 The full dotted name of the module the type is defined in, like
441 ``numpy``.
442 ``numpy``.
442 type_name : str
443 type_name : str
443 The name of the type (the class name), like ``dtype``
444 The name of the type (the class name), like ``dtype``
444 func : callable
445 func : callable
445 A callable for computing the format data.
446 A callable for computing the format data.
446 `func` will be called with the object to be formatted,
447 `func` will be called with the object to be formatted,
447 and will return the raw data in this formatter's format.
448 and will return the raw data in this formatter's format.
448 Subclasses may use a different call signature for the
449 Subclasses may use a different call signature for the
449 `func` argument.
450 `func` argument.
450
451
451 If `func` is None or unspecified, there will be no change,
452 If `func` is None or unspecified, there will be no change,
452 only returning the current value.
453 only returning the current value.
453
454
454 Returns
455 Returns
455 -------
456 -------
456 oldfunc : callable
457 oldfunc : callable
457 The currently registered callable.
458 The currently registered callable.
458 If you are registering a new formatter,
459 If you are registering a new formatter,
459 this will be the previous value (to enable restoring later).
460 this will be the previous value (to enable restoring later).
460 """
461 """
461 key = (type_module, type_name)
462 key = (type_module, type_name)
462
463
463 try:
464 try:
464 oldfunc = self.lookup_by_type("%s.%s" % key)
465 oldfunc = self.lookup_by_type("%s.%s" % key)
465 except KeyError:
466 except KeyError:
466 oldfunc = None
467 oldfunc = None
467
468
468 if func is not None:
469 if func is not None:
469 self.deferred_printers[key] = func
470 self.deferred_printers[key] = func
470 return oldfunc
471 return oldfunc
471
472
472 def pop(self, typ, default=_raise_key_error):
473 def pop(self, typ, default=_raise_key_error):
473 """Pop a formatter for the given type.
474 """Pop a formatter for the given type.
474
475
475 Parameters
476 Parameters
476 ----------
477 ----------
477 typ : type or '__module__.__name__' string for a type
478 typ : type or '__module__.__name__' string for a type
478 default : object
479 default : object
479 value to be returned if no formatter is registered for typ.
480 value to be returned if no formatter is registered for typ.
480
481
481 Returns
482 Returns
482 -------
483 -------
483 obj : object
484 obj : object
484 The last registered object for the type.
485 The last registered object for the type.
485
486
486 Raises
487 Raises
487 ------
488 ------
488 KeyError if the type is not registered and default is not specified.
489 KeyError if the type is not registered and default is not specified.
489 """
490 """
490
491
491 if isinstance(typ, str):
492 if isinstance(typ, str):
492 typ_key = tuple(typ.rsplit('.',1))
493 typ_key = tuple(typ.rsplit('.',1))
493 if typ_key not in self.deferred_printers:
494 if typ_key not in self.deferred_printers:
494 # We may have it cached in the type map. We will have to
495 # We may have it cached in the type map. We will have to
495 # iterate over all of the types to check.
496 # iterate over all of the types to check.
496 for cls in self.type_printers:
497 for cls in self.type_printers:
497 if _mod_name_key(cls) == typ_key:
498 if _mod_name_key(cls) == typ_key:
498 old = self.type_printers.pop(cls)
499 old = self.type_printers.pop(cls)
499 break
500 break
500 else:
501 else:
501 old = default
502 old = default
502 else:
503 else:
503 old = self.deferred_printers.pop(typ_key)
504 old = self.deferred_printers.pop(typ_key)
504 else:
505 else:
505 if typ in self.type_printers:
506 if typ in self.type_printers:
506 old = self.type_printers.pop(typ)
507 old = self.type_printers.pop(typ)
507 else:
508 else:
508 old = self.deferred_printers.pop(_mod_name_key(typ), default)
509 old = self.deferred_printers.pop(_mod_name_key(typ), default)
509 if old is _raise_key_error:
510 if old is _raise_key_error:
510 raise KeyError("No registered value for {0!r}".format(typ))
511 raise KeyError("No registered value for {0!r}".format(typ))
511 return old
512 return old
512
513
513 def _in_deferred_types(self, cls):
514 def _in_deferred_types(self, cls):
514 """
515 """
515 Check if the given class is specified in the deferred type registry.
516 Check if the given class is specified in the deferred type registry.
516
517
517 Successful matches will be moved to the regular type registry for future use.
518 Successful matches will be moved to the regular type registry for future use.
518 """
519 """
519 mod = getattr(cls, '__module__', None)
520 mod = getattr(cls, '__module__', None)
520 name = getattr(cls, '__name__', None)
521 name = getattr(cls, '__name__', None)
521 key = (mod, name)
522 key = (mod, name)
522 if key in self.deferred_printers:
523 if key in self.deferred_printers:
523 # Move the printer over to the regular registry.
524 # Move the printer over to the regular registry.
524 printer = self.deferred_printers.pop(key)
525 printer = self.deferred_printers.pop(key)
525 self.type_printers[cls] = printer
526 self.type_printers[cls] = printer
526 return True
527 return True
527 return False
528 return False
528
529
529
530
530 class PlainTextFormatter(BaseFormatter):
531 class PlainTextFormatter(BaseFormatter):
531 """The default pretty-printer.
532 """The default pretty-printer.
532
533
533 This uses :mod:`IPython.lib.pretty` to compute the format data of
534 This uses :mod:`IPython.lib.pretty` to compute the format data of
534 the object. If the object cannot be pretty printed, :func:`repr` is used.
535 the object. If the object cannot be pretty printed, :func:`repr` is used.
535 See the documentation of :mod:`IPython.lib.pretty` for details on
536 See the documentation of :mod:`IPython.lib.pretty` for details on
536 how to write pretty printers. Here is a simple example::
537 how to write pretty printers. Here is a simple example::
537
538
538 def dtype_pprinter(obj, p, cycle):
539 def dtype_pprinter(obj, p, cycle):
539 if cycle:
540 if cycle:
540 return p.text('dtype(...)')
541 return p.text('dtype(...)')
541 if hasattr(obj, 'fields'):
542 if hasattr(obj, 'fields'):
542 if obj.fields is None:
543 if obj.fields is None:
543 p.text(repr(obj))
544 p.text(repr(obj))
544 else:
545 else:
545 p.begin_group(7, 'dtype([')
546 p.begin_group(7, 'dtype([')
546 for i, field in enumerate(obj.descr):
547 for i, field in enumerate(obj.descr):
547 if i > 0:
548 if i > 0:
548 p.text(',')
549 p.text(',')
549 p.breakable()
550 p.breakable()
550 p.pretty(field)
551 p.pretty(field)
551 p.end_group(7, '])')
552 p.end_group(7, '])')
552 """
553 """
553
554
554 # The format type of data returned.
555 # The format type of data returned.
555 format_type = Unicode('text/plain')
556 format_type = Unicode('text/plain')
556
557
557 # This subclass ignores this attribute as it always need to return
558 # This subclass ignores this attribute as it always need to return
558 # something.
559 # something.
559 enabled = Bool(True).tag(config=False)
560 enabled = Bool(True).tag(config=False)
560
561
561 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
562 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
562 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
563 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
563
564
564 Set to 0 to disable truncation.
565 Set to 0 to disable truncation.
565 """
566 """
566 ).tag(config=True)
567 ).tag(config=True)
567
568
568 # Look for a _repr_pretty_ methods to use for pretty printing.
569 # Look for a _repr_pretty_ methods to use for pretty printing.
569 print_method = ObjectName('_repr_pretty_')
570 print_method = ObjectName('_repr_pretty_')
570
571
571 # Whether to pretty-print or not.
572 # Whether to pretty-print or not.
572 pprint = Bool(True).tag(config=True)
573 pprint = Bool(True).tag(config=True)
573
574
574 # Whether to be verbose or not.
575 # Whether to be verbose or not.
575 verbose = Bool(False).tag(config=True)
576 verbose = Bool(False).tag(config=True)
576
577
577 # The maximum width.
578 # The maximum width.
578 max_width = Integer(79).tag(config=True)
579 max_width = Integer(79).tag(config=True)
579
580
580 # The newline character.
581 # The newline character.
581 newline = Unicode('\n').tag(config=True)
582 newline = Unicode('\n').tag(config=True)
582
583
583 # format-string for pprinting floats
584 # format-string for pprinting floats
584 float_format = Unicode('%r')
585 float_format = Unicode('%r')
585 # setter for float precision, either int or direct format-string
586 # setter for float precision, either int or direct format-string
586 float_precision = CUnicode('').tag(config=True)
587 float_precision = CUnicode('').tag(config=True)
587
588
588 @observe('float_precision')
589 @observe('float_precision')
589 def _float_precision_changed(self, change):
590 def _float_precision_changed(self, change):
590 """float_precision changed, set float_format accordingly.
591 """float_precision changed, set float_format accordingly.
591
592
592 float_precision can be set by int or str.
593 float_precision can be set by int or str.
593 This will set float_format, after interpreting input.
594 This will set float_format, after interpreting input.
594 If numpy has been imported, numpy print precision will also be set.
595 If numpy has been imported, numpy print precision will also be set.
595
596
596 integer `n` sets format to '%.nf', otherwise, format set directly.
597 integer `n` sets format to '%.nf', otherwise, format set directly.
597
598
598 An empty string returns to defaults (repr for float, 8 for numpy).
599 An empty string returns to defaults (repr for float, 8 for numpy).
599
600
600 This parameter can be set via the '%precision' magic.
601 This parameter can be set via the '%precision' magic.
601 """
602 """
602
603
603 new = change['new']
604 new = change['new']
604 if '%' in new:
605 if '%' in new:
605 # got explicit format string
606 # got explicit format string
606 fmt = new
607 fmt = new
607 try:
608 try:
608 fmt%3.14159
609 fmt%3.14159
609 except Exception:
610 except Exception:
610 raise ValueError("Precision must be int or format string, not %r"%new)
611 raise ValueError("Precision must be int or format string, not %r"%new)
611 elif new:
612 elif new:
612 # otherwise, should be an int
613 # otherwise, should be an int
613 try:
614 try:
614 i = int(new)
615 i = int(new)
615 assert i >= 0
616 assert i >= 0
616 except ValueError:
617 except ValueError:
617 raise ValueError("Precision must be int or format string, not %r"%new)
618 raise ValueError("Precision must be int or format string, not %r"%new)
618 except AssertionError:
619 except AssertionError:
619 raise ValueError("int precision must be non-negative, not %r"%i)
620 raise ValueError("int precision must be non-negative, not %r"%i)
620
621
621 fmt = '%%.%if'%i
622 fmt = '%%.%if'%i
622 if 'numpy' in sys.modules:
623 if 'numpy' in sys.modules:
623 # set numpy precision if it has been imported
624 # set numpy precision if it has been imported
624 import numpy
625 import numpy
625 numpy.set_printoptions(precision=i)
626 numpy.set_printoptions(precision=i)
626 else:
627 else:
627 # default back to repr
628 # default back to repr
628 fmt = '%r'
629 fmt = '%r'
629 if 'numpy' in sys.modules:
630 if 'numpy' in sys.modules:
630 import numpy
631 import numpy
631 # numpy default is 8
632 # numpy default is 8
632 numpy.set_printoptions(precision=8)
633 numpy.set_printoptions(precision=8)
633 self.float_format = fmt
634 self.float_format = fmt
634
635
635 # Use the default pretty printers from IPython.lib.pretty.
636 # Use the default pretty printers from IPython.lib.pretty.
636 @default('singleton_printers')
637 @default('singleton_printers')
637 def _singleton_printers_default(self):
638 def _singleton_printers_default(self):
638 return pretty._singleton_pprinters.copy()
639 return pretty._singleton_pprinters.copy()
639
640
640 @default('type_printers')
641 @default('type_printers')
641 def _type_printers_default(self):
642 def _type_printers_default(self):
642 d = pretty._type_pprinters.copy()
643 d = pretty._type_pprinters.copy()
643 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
644 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
644 return d
645 return d
645
646
646 @default('deferred_printers')
647 @default('deferred_printers')
647 def _deferred_printers_default(self):
648 def _deferred_printers_default(self):
648 return pretty._deferred_type_pprinters.copy()
649 return pretty._deferred_type_pprinters.copy()
649
650
650 #### FormatterABC interface ####
651 #### FormatterABC interface ####
651
652
652 @catch_format_error
653 @catch_format_error
653 def __call__(self, obj):
654 def __call__(self, obj):
654 """Compute the pretty representation of the object."""
655 """Compute the pretty representation of the object."""
655 if not self.pprint:
656 if not self.pprint:
656 return repr(obj)
657 return repr(obj)
657 else:
658 else:
658 # handle str and unicode on Python 2
659 stream = StringIO()
659 # io.StringIO only accepts unicode,
660 # cStringIO doesn't handle unicode on py2,
661 # StringIO allows str, unicode but only ascii str
662 stream = pretty.CUnicodeIO()
663 printer = pretty.RepresentationPrinter(stream, self.verbose,
660 printer = pretty.RepresentationPrinter(stream, self.verbose,
664 self.max_width, self.newline,
661 self.max_width, self.newline,
665 max_seq_length=self.max_seq_length,
662 max_seq_length=self.max_seq_length,
666 singleton_pprinters=self.singleton_printers,
663 singleton_pprinters=self.singleton_printers,
667 type_pprinters=self.type_printers,
664 type_pprinters=self.type_printers,
668 deferred_pprinters=self.deferred_printers)
665 deferred_pprinters=self.deferred_printers)
669 printer.pretty(obj)
666 printer.pretty(obj)
670 printer.flush()
667 printer.flush()
671 return stream.getvalue()
668 return stream.getvalue()
672
669
673
670
674 class HTMLFormatter(BaseFormatter):
671 class HTMLFormatter(BaseFormatter):
675 """An HTML formatter.
672 """An HTML formatter.
676
673
677 To define the callables that compute the HTML representation of your
674 To define the callables that compute the HTML representation of your
678 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
675 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
679 or :meth:`for_type_by_name` methods to register functions that handle
676 or :meth:`for_type_by_name` methods to register functions that handle
680 this.
677 this.
681
678
682 The return value of this formatter should be a valid HTML snippet that
679 The return value of this formatter should be a valid HTML snippet that
683 could be injected into an existing DOM. It should *not* include the
680 could be injected into an existing DOM. It should *not* include the
684 ```<html>`` or ```<body>`` tags.
681 ```<html>`` or ```<body>`` tags.
685 """
682 """
686 format_type = Unicode('text/html')
683 format_type = Unicode('text/html')
687
684
688 print_method = ObjectName('_repr_html_')
685 print_method = ObjectName('_repr_html_')
689
686
690
687
691 class MarkdownFormatter(BaseFormatter):
688 class MarkdownFormatter(BaseFormatter):
692 """A Markdown formatter.
689 """A Markdown formatter.
693
690
694 To define the callables that compute the Markdown representation of your
691 To define the callables that compute the Markdown representation of your
695 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
692 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
696 or :meth:`for_type_by_name` methods to register functions that handle
693 or :meth:`for_type_by_name` methods to register functions that handle
697 this.
694 this.
698
695
699 The return value of this formatter should be a valid Markdown.
696 The return value of this formatter should be a valid Markdown.
700 """
697 """
701 format_type = Unicode('text/markdown')
698 format_type = Unicode('text/markdown')
702
699
703 print_method = ObjectName('_repr_markdown_')
700 print_method = ObjectName('_repr_markdown_')
704
701
705 class SVGFormatter(BaseFormatter):
702 class SVGFormatter(BaseFormatter):
706 """An SVG formatter.
703 """An SVG formatter.
707
704
708 To define the callables that compute the SVG representation of your
705 To define the callables that compute the SVG representation of your
709 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
706 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
710 or :meth:`for_type_by_name` methods to register functions that handle
707 or :meth:`for_type_by_name` methods to register functions that handle
711 this.
708 this.
712
709
713 The return value of this formatter should be valid SVG enclosed in
710 The return value of this formatter should be valid SVG enclosed in
714 ```<svg>``` tags, that could be injected into an existing DOM. It should
711 ```<svg>``` tags, that could be injected into an existing DOM. It should
715 *not* include the ```<html>`` or ```<body>`` tags.
712 *not* include the ```<html>`` or ```<body>`` tags.
716 """
713 """
717 format_type = Unicode('image/svg+xml')
714 format_type = Unicode('image/svg+xml')
718
715
719 print_method = ObjectName('_repr_svg_')
716 print_method = ObjectName('_repr_svg_')
720
717
721
718
722 class PNGFormatter(BaseFormatter):
719 class PNGFormatter(BaseFormatter):
723 """A PNG formatter.
720 """A PNG formatter.
724
721
725 To define the callables that compute the PNG representation of your
722 To define the callables that compute the PNG representation of your
726 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
723 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
727 or :meth:`for_type_by_name` methods to register functions that handle
724 or :meth:`for_type_by_name` methods to register functions that handle
728 this.
725 this.
729
726
730 The return value of this formatter should be raw PNG data, *not*
727 The return value of this formatter should be raw PNG data, *not*
731 base64 encoded.
728 base64 encoded.
732 """
729 """
733 format_type = Unicode('image/png')
730 format_type = Unicode('image/png')
734
731
735 print_method = ObjectName('_repr_png_')
732 print_method = ObjectName('_repr_png_')
736
733
737 _return_type = (bytes, str)
734 _return_type = (bytes, str)
738
735
739
736
740 class JPEGFormatter(BaseFormatter):
737 class JPEGFormatter(BaseFormatter):
741 """A JPEG formatter.
738 """A JPEG formatter.
742
739
743 To define the callables that compute the JPEG representation of your
740 To define the callables that compute the JPEG representation of your
744 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
741 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
745 or :meth:`for_type_by_name` methods to register functions that handle
742 or :meth:`for_type_by_name` methods to register functions that handle
746 this.
743 this.
747
744
748 The return value of this formatter should be raw JPEG data, *not*
745 The return value of this formatter should be raw JPEG data, *not*
749 base64 encoded.
746 base64 encoded.
750 """
747 """
751 format_type = Unicode('image/jpeg')
748 format_type = Unicode('image/jpeg')
752
749
753 print_method = ObjectName('_repr_jpeg_')
750 print_method = ObjectName('_repr_jpeg_')
754
751
755 _return_type = (bytes, str)
752 _return_type = (bytes, str)
756
753
757
754
758 class LatexFormatter(BaseFormatter):
755 class LatexFormatter(BaseFormatter):
759 """A LaTeX formatter.
756 """A LaTeX formatter.
760
757
761 To define the callables that compute the LaTeX representation of your
758 To define the callables that compute the LaTeX representation of your
762 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
759 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
763 or :meth:`for_type_by_name` methods to register functions that handle
760 or :meth:`for_type_by_name` methods to register functions that handle
764 this.
761 this.
765
762
766 The return value of this formatter should be a valid LaTeX equation,
763 The return value of this formatter should be a valid LaTeX equation,
767 enclosed in either ```$```, ```$$``` or another LaTeX equation
764 enclosed in either ```$```, ```$$``` or another LaTeX equation
768 environment.
765 environment.
769 """
766 """
770 format_type = Unicode('text/latex')
767 format_type = Unicode('text/latex')
771
768
772 print_method = ObjectName('_repr_latex_')
769 print_method = ObjectName('_repr_latex_')
773
770
774
771
775 class JSONFormatter(BaseFormatter):
772 class JSONFormatter(BaseFormatter):
776 """A JSON string formatter.
773 """A JSON string formatter.
777
774
778 To define the callables that compute the JSONable representation of
775 To define the callables that compute the JSONable representation of
779 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
776 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
780 or :meth:`for_type_by_name` methods to register functions that handle
777 or :meth:`for_type_by_name` methods to register functions that handle
781 this.
778 this.
782
779
783 The return value of this formatter should be a JSONable list or dict.
780 The return value of this formatter should be a JSONable list or dict.
784 JSON scalars (None, number, string) are not allowed, only dict or list containers.
781 JSON scalars (None, number, string) are not allowed, only dict or list containers.
785 """
782 """
786 format_type = Unicode('application/json')
783 format_type = Unicode('application/json')
787 _return_type = (list, dict)
784 _return_type = (list, dict)
788
785
789 print_method = ObjectName('_repr_json_')
786 print_method = ObjectName('_repr_json_')
790
787
791 def _check_return(self, r, obj):
788 def _check_return(self, r, obj):
792 """Check that a return value is appropriate
789 """Check that a return value is appropriate
793
790
794 Return the value if so, None otherwise, warning if invalid.
791 Return the value if so, None otherwise, warning if invalid.
795 """
792 """
796 if r is None:
793 if r is None:
797 return
794 return
798 md = None
795 md = None
799 if isinstance(r, tuple):
796 if isinstance(r, tuple):
800 # unpack data, metadata tuple for type checking on first element
797 # unpack data, metadata tuple for type checking on first element
801 r, md = r
798 r, md = r
802
799
803 # handle deprecated JSON-as-string form from IPython < 3
800 # handle deprecated JSON-as-string form from IPython < 3
804 if isinstance(r, str):
801 if isinstance(r, str):
805 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
802 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
806 FormatterWarning)
803 FormatterWarning)
807 r = json.loads(r)
804 r = json.loads(r)
808
805
809 if md is not None:
806 if md is not None:
810 # put the tuple back together
807 # put the tuple back together
811 r = (r, md)
808 r = (r, md)
812 return super(JSONFormatter, self)._check_return(r, obj)
809 return super(JSONFormatter, self)._check_return(r, obj)
813
810
814
811
815 class JavascriptFormatter(BaseFormatter):
812 class JavascriptFormatter(BaseFormatter):
816 """A Javascript formatter.
813 """A Javascript formatter.
817
814
818 To define the callables that compute the Javascript representation of
815 To define the callables that compute the Javascript representation of
819 your objects, define a :meth:`_repr_javascript_` method or use the
816 your objects, define a :meth:`_repr_javascript_` method or use the
820 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
817 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
821 that handle this.
818 that handle this.
822
819
823 The return value of this formatter should be valid Javascript code and
820 The return value of this formatter should be valid Javascript code and
824 should *not* be enclosed in ```<script>``` tags.
821 should *not* be enclosed in ```<script>``` tags.
825 """
822 """
826 format_type = Unicode('application/javascript')
823 format_type = Unicode('application/javascript')
827
824
828 print_method = ObjectName('_repr_javascript_')
825 print_method = ObjectName('_repr_javascript_')
829
826
830
827
831 class PDFFormatter(BaseFormatter):
828 class PDFFormatter(BaseFormatter):
832 """A PDF formatter.
829 """A PDF formatter.
833
830
834 To define the callables that compute the PDF representation of your
831 To define the callables that compute the PDF representation of your
835 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
832 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
836 or :meth:`for_type_by_name` methods to register functions that handle
833 or :meth:`for_type_by_name` methods to register functions that handle
837 this.
834 this.
838
835
839 The return value of this formatter should be raw PDF data, *not*
836 The return value of this formatter should be raw PDF data, *not*
840 base64 encoded.
837 base64 encoded.
841 """
838 """
842 format_type = Unicode('application/pdf')
839 format_type = Unicode('application/pdf')
843
840
844 print_method = ObjectName('_repr_pdf_')
841 print_method = ObjectName('_repr_pdf_')
845
842
846 _return_type = (bytes, str)
843 _return_type = (bytes, str)
847
844
848 class IPythonDisplayFormatter(BaseFormatter):
845 class IPythonDisplayFormatter(BaseFormatter):
849 """A Formatter for objects that know how to display themselves.
846 """A Formatter for objects that know how to display themselves.
850
847
851 To define the callables that compute the representation of your
848 To define the callables that compute the representation of your
852 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
849 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
853 or :meth:`for_type_by_name` methods to register functions that handle
850 or :meth:`for_type_by_name` methods to register functions that handle
854 this. Unlike mime-type displays, this method should not return anything,
851 this. Unlike mime-type displays, this method should not return anything,
855 instead calling any appropriate display methods itself.
852 instead calling any appropriate display methods itself.
856
853
857 This display formatter has highest priority.
854 This display formatter has highest priority.
858 If it fires, no other display formatter will be called.
855 If it fires, no other display formatter will be called.
859 """
856 """
860 print_method = ObjectName('_ipython_display_')
857 print_method = ObjectName('_ipython_display_')
861 _return_type = (type(None), bool)
858 _return_type = (type(None), bool)
862
859
863
860
864 @catch_format_error
861 @catch_format_error
865 def __call__(self, obj):
862 def __call__(self, obj):
866 """Compute the format for an object."""
863 """Compute the format for an object."""
867 if self.enabled:
864 if self.enabled:
868 # lookup registered printer
865 # lookup registered printer
869 try:
866 try:
870 printer = self.lookup(obj)
867 printer = self.lookup(obj)
871 except KeyError:
868 except KeyError:
872 pass
869 pass
873 else:
870 else:
874 printer(obj)
871 printer(obj)
875 return True
872 return True
876 # Finally look for special method names
873 # Finally look for special method names
877 method = get_real_method(obj, self.print_method)
874 method = get_real_method(obj, self.print_method)
878 if method is not None:
875 if method is not None:
879 method()
876 method()
880 return True
877 return True
881
878
882
879
883 FormatterABC.register(BaseFormatter)
880 FormatterABC.register(BaseFormatter)
884 FormatterABC.register(PlainTextFormatter)
881 FormatterABC.register(PlainTextFormatter)
885 FormatterABC.register(HTMLFormatter)
882 FormatterABC.register(HTMLFormatter)
886 FormatterABC.register(MarkdownFormatter)
883 FormatterABC.register(MarkdownFormatter)
887 FormatterABC.register(SVGFormatter)
884 FormatterABC.register(SVGFormatter)
888 FormatterABC.register(PNGFormatter)
885 FormatterABC.register(PNGFormatter)
889 FormatterABC.register(PDFFormatter)
886 FormatterABC.register(PDFFormatter)
890 FormatterABC.register(JPEGFormatter)
887 FormatterABC.register(JPEGFormatter)
891 FormatterABC.register(LatexFormatter)
888 FormatterABC.register(LatexFormatter)
892 FormatterABC.register(JSONFormatter)
889 FormatterABC.register(JSONFormatter)
893 FormatterABC.register(JavascriptFormatter)
890 FormatterABC.register(JavascriptFormatter)
894 FormatterABC.register(IPythonDisplayFormatter)
891 FormatterABC.register(IPythonDisplayFormatter)
895
892
896
893
897 def format_display_data(obj, include=None, exclude=None):
894 def format_display_data(obj, include=None, exclude=None):
898 """Return a format data dict for an object.
895 """Return a format data dict for an object.
899
896
900 By default all format types will be computed.
897 By default all format types will be computed.
901
898
902 The following MIME types are currently implemented:
899 The following MIME types are currently implemented:
903
900
904 * text/plain
901 * text/plain
905 * text/html
902 * text/html
906 * text/markdown
903 * text/markdown
907 * text/latex
904 * text/latex
908 * application/json
905 * application/json
909 * application/javascript
906 * application/javascript
910 * application/pdf
907 * application/pdf
911 * image/png
908 * image/png
912 * image/jpeg
909 * image/jpeg
913 * image/svg+xml
910 * image/svg+xml
914
911
915 Parameters
912 Parameters
916 ----------
913 ----------
917 obj : object
914 obj : object
918 The Python object whose format data will be computed.
915 The Python object whose format data will be computed.
919
916
920 Returns
917 Returns
921 -------
918 -------
922 format_dict : dict
919 format_dict : dict
923 A dictionary of key/value pairs, one or each format that was
920 A dictionary of key/value pairs, one or each format that was
924 generated for the object. The keys are the format types, which
921 generated for the object. The keys are the format types, which
925 will usually be MIME type strings and the values and JSON'able
922 will usually be MIME type strings and the values and JSON'able
926 data structure containing the raw data for the representation in
923 data structure containing the raw data for the representation in
927 that format.
924 that format.
928 include : list or tuple, optional
925 include : list or tuple, optional
929 A list of format type strings (MIME types) to include in the
926 A list of format type strings (MIME types) to include in the
930 format data dict. If this is set *only* the format types included
927 format data dict. If this is set *only* the format types included
931 in this list will be computed.
928 in this list will be computed.
932 exclude : list or tuple, optional
929 exclude : list or tuple, optional
933 A list of format type string (MIME types) to exclue in the format
930 A list of format type string (MIME types) to exclue in the format
934 data dict. If this is set all format types will be computed,
931 data dict. If this is set all format types will be computed,
935 except for those included in this argument.
932 except for those included in this argument.
936 """
933 """
937 from IPython.core.interactiveshell import InteractiveShell
934 from IPython.core.interactiveshell import InteractiveShell
938
935
939 return InteractiveShell.instance().display_formatter.format(
936 return InteractiveShell.instance().display_formatter.format(
940 obj,
937 obj,
941 include,
938 include,
942 exclude
939 exclude
943 )
940 )
944
941
@@ -1,858 +1,857 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Python advanced pretty printer. This pretty printer is intended to
3 Python advanced pretty printer. This pretty printer is intended to
4 replace the old `pprint` python module which does not allow developers
4 replace the old `pprint` python module which does not allow developers
5 to provide their own pretty print callbacks.
5 to provide their own pretty print callbacks.
6
6
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8
8
9
9
10 Example Usage
10 Example Usage
11 -------------
11 -------------
12
12
13 To directly print the representation of an object use `pprint`::
13 To directly print the representation of an object use `pprint`::
14
14
15 from pretty import pprint
15 from pretty import pprint
16 pprint(complex_object)
16 pprint(complex_object)
17
17
18 To get a string of the output use `pretty`::
18 To get a string of the output use `pretty`::
19
19
20 from pretty import pretty
20 from pretty import pretty
21 string = pretty(complex_object)
21 string = pretty(complex_object)
22
22
23
23
24 Extending
24 Extending
25 ---------
25 ---------
26
26
27 The pretty library allows developers to add pretty printing rules for their
27 The pretty library allows developers to add pretty printing rules for their
28 own objects. This process is straightforward. All you have to do is to
28 own objects. This process is straightforward. All you have to do is to
29 add a `_repr_pretty_` method to your object and call the methods on the
29 add a `_repr_pretty_` method to your object and call the methods on the
30 pretty printer passed::
30 pretty printer passed::
31
31
32 class MyObject(object):
32 class MyObject(object):
33
33
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 ...
35 ...
36
36
37 Here is an example implementation of a `_repr_pretty_` method for a list
37 Here is an example implementation of a `_repr_pretty_` method for a list
38 subclass::
38 subclass::
39
39
40 class MyList(list):
40 class MyList(list):
41
41
42 def _repr_pretty_(self, p, cycle):
42 def _repr_pretty_(self, p, cycle):
43 if cycle:
43 if cycle:
44 p.text('MyList(...)')
44 p.text('MyList(...)')
45 else:
45 else:
46 with p.group(8, 'MyList([', '])'):
46 with p.group(8, 'MyList([', '])'):
47 for idx, item in enumerate(self):
47 for idx, item in enumerate(self):
48 if idx:
48 if idx:
49 p.text(',')
49 p.text(',')
50 p.breakable()
50 p.breakable()
51 p.pretty(item)
51 p.pretty(item)
52
52
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
54 react to that or the result is an infinite loop. `p.text()` just adds
54 react to that or the result is an infinite loop. `p.text()` just adds
55 non breaking text to the output, `p.breakable()` either adds a whitespace
55 non breaking text to the output, `p.breakable()` either adds a whitespace
56 or breaks here. If you pass it an argument it's used instead of the
56 or breaks here. If you pass it an argument it's used instead of the
57 default space. `p.pretty` prettyprints another object using the pretty print
57 default space. `p.pretty` prettyprints another object using the pretty print
58 method.
58 method.
59
59
60 The first parameter to the `group` function specifies the extra indentation
60 The first parameter to the `group` function specifies the extra indentation
61 of the next line. In this example the next item will either be on the same
61 of the next line. In this example the next item will either be on the same
62 line (if the items are short enough) or aligned with the right edge of the
62 line (if the items are short enough) or aligned with the right edge of the
63 opening bracket of `MyList`.
63 opening bracket of `MyList`.
64
64
65 If you just want to indent something you can use the group function
65 If you just want to indent something you can use the group function
66 without open / close parameters. You can also use this code::
66 without open / close parameters. You can also use this code::
67
67
68 with p.indent(2):
68 with p.indent(2):
69 ...
69 ...
70
70
71 Inheritance diagram:
71 Inheritance diagram:
72
72
73 .. inheritance-diagram:: IPython.lib.pretty
73 .. inheritance-diagram:: IPython.lib.pretty
74 :parts: 3
74 :parts: 3
75
75
76 :copyright: 2007 by Armin Ronacher.
76 :copyright: 2007 by Armin Ronacher.
77 Portions (c) 2009 by Robert Kern.
77 Portions (c) 2009 by Robert Kern.
78 :license: BSD License.
78 :license: BSD License.
79 """
79 """
80 from contextlib import contextmanager
80 from contextlib import contextmanager
81 import sys
81 import sys
82 import types
82 import types
83 import re
83 import re
84 import datetime
84 import datetime
85 from collections import deque
85 from collections import deque
86 from io import StringIO
86
87
87 from IPython.utils.py3compat import PYPY, cast_unicode
88 from IPython.utils.py3compat import PYPY, cast_unicode
88 from IPython.utils.encoding import get_stream_enc
89 from IPython.utils.encoding import get_stream_enc
89
90
90 from io import StringIO
91
92
91
93 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
92 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
94 'for_type', 'for_type_by_name']
93 'for_type', 'for_type_by_name']
95
94
96
95
97 MAX_SEQ_LENGTH = 1000
96 MAX_SEQ_LENGTH = 1000
98 _re_pattern_type = type(re.compile(''))
97 _re_pattern_type = type(re.compile(''))
99
98
100 def _safe_getattr(obj, attr, default=None):
99 def _safe_getattr(obj, attr, default=None):
101 """Safe version of getattr.
100 """Safe version of getattr.
102
101
103 Same as getattr, but will return ``default`` on any Exception,
102 Same as getattr, but will return ``default`` on any Exception,
104 rather than raising.
103 rather than raising.
105 """
104 """
106 try:
105 try:
107 return getattr(obj, attr, default)
106 return getattr(obj, attr, default)
108 except Exception:
107 except Exception:
109 return default
108 return default
110
109
111 CUnicodeIO = StringIO
110 CUnicodeIO = StringIO
112
111
113 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
112 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
114 """
113 """
115 Pretty print the object's representation.
114 Pretty print the object's representation.
116 """
115 """
117 stream = CUnicodeIO()
116 stream = StringIO()
118 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
117 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
119 printer.pretty(obj)
118 printer.pretty(obj)
120 printer.flush()
119 printer.flush()
121 return stream.getvalue()
120 return stream.getvalue()
122
121
123
122
124 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
123 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
125 """
124 """
126 Like `pretty` but print to stdout.
125 Like `pretty` but print to stdout.
127 """
126 """
128 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
127 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
129 printer.pretty(obj)
128 printer.pretty(obj)
130 printer.flush()
129 printer.flush()
131 sys.stdout.write(newline)
130 sys.stdout.write(newline)
132 sys.stdout.flush()
131 sys.stdout.flush()
133
132
134 class _PrettyPrinterBase(object):
133 class _PrettyPrinterBase(object):
135
134
136 @contextmanager
135 @contextmanager
137 def indent(self, indent):
136 def indent(self, indent):
138 """with statement support for indenting/dedenting."""
137 """with statement support for indenting/dedenting."""
139 self.indentation += indent
138 self.indentation += indent
140 try:
139 try:
141 yield
140 yield
142 finally:
141 finally:
143 self.indentation -= indent
142 self.indentation -= indent
144
143
145 @contextmanager
144 @contextmanager
146 def group(self, indent=0, open='', close=''):
145 def group(self, indent=0, open='', close=''):
147 """like begin_group / end_group but for the with statement."""
146 """like begin_group / end_group but for the with statement."""
148 self.begin_group(indent, open)
147 self.begin_group(indent, open)
149 try:
148 try:
150 yield
149 yield
151 finally:
150 finally:
152 self.end_group(indent, close)
151 self.end_group(indent, close)
153
152
154 class PrettyPrinter(_PrettyPrinterBase):
153 class PrettyPrinter(_PrettyPrinterBase):
155 """
154 """
156 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
155 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
157 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
156 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
158 this printer knows nothing about the default pprinters or the `_repr_pretty_`
157 this printer knows nothing about the default pprinters or the `_repr_pretty_`
159 callback method.
158 callback method.
160 """
159 """
161
160
162 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
161 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
163 self.output = output
162 self.output = output
164 self.max_width = max_width
163 self.max_width = max_width
165 self.newline = newline
164 self.newline = newline
166 self.max_seq_length = max_seq_length
165 self.max_seq_length = max_seq_length
167 self.output_width = 0
166 self.output_width = 0
168 self.buffer_width = 0
167 self.buffer_width = 0
169 self.buffer = deque()
168 self.buffer = deque()
170
169
171 root_group = Group(0)
170 root_group = Group(0)
172 self.group_stack = [root_group]
171 self.group_stack = [root_group]
173 self.group_queue = GroupQueue(root_group)
172 self.group_queue = GroupQueue(root_group)
174 self.indentation = 0
173 self.indentation = 0
175
174
176 def _break_outer_groups(self):
175 def _break_outer_groups(self):
177 while self.max_width < self.output_width + self.buffer_width:
176 while self.max_width < self.output_width + self.buffer_width:
178 group = self.group_queue.deq()
177 group = self.group_queue.deq()
179 if not group:
178 if not group:
180 return
179 return
181 while group.breakables:
180 while group.breakables:
182 x = self.buffer.popleft()
181 x = self.buffer.popleft()
183 self.output_width = x.output(self.output, self.output_width)
182 self.output_width = x.output(self.output, self.output_width)
184 self.buffer_width -= x.width
183 self.buffer_width -= x.width
185 while self.buffer and isinstance(self.buffer[0], Text):
184 while self.buffer and isinstance(self.buffer[0], Text):
186 x = self.buffer.popleft()
185 x = self.buffer.popleft()
187 self.output_width = x.output(self.output, self.output_width)
186 self.output_width = x.output(self.output, self.output_width)
188 self.buffer_width -= x.width
187 self.buffer_width -= x.width
189
188
190 def text(self, obj):
189 def text(self, obj):
191 """Add literal text to the output."""
190 """Add literal text to the output."""
192 width = len(obj)
191 width = len(obj)
193 if self.buffer:
192 if self.buffer:
194 text = self.buffer[-1]
193 text = self.buffer[-1]
195 if not isinstance(text, Text):
194 if not isinstance(text, Text):
196 text = Text()
195 text = Text()
197 self.buffer.append(text)
196 self.buffer.append(text)
198 text.add(obj, width)
197 text.add(obj, width)
199 self.buffer_width += width
198 self.buffer_width += width
200 self._break_outer_groups()
199 self._break_outer_groups()
201 else:
200 else:
202 self.output.write(obj)
201 self.output.write(obj)
203 self.output_width += width
202 self.output_width += width
204
203
205 def breakable(self, sep=' '):
204 def breakable(self, sep=' '):
206 """
205 """
207 Add a breakable separator to the output. This does not mean that it
206 Add a breakable separator to the output. This does not mean that it
208 will automatically break here. If no breaking on this position takes
207 will automatically break here. If no breaking on this position takes
209 place the `sep` is inserted which default to one space.
208 place the `sep` is inserted which default to one space.
210 """
209 """
211 width = len(sep)
210 width = len(sep)
212 group = self.group_stack[-1]
211 group = self.group_stack[-1]
213 if group.want_break:
212 if group.want_break:
214 self.flush()
213 self.flush()
215 self.output.write(self.newline)
214 self.output.write(self.newline)
216 self.output.write(' ' * self.indentation)
215 self.output.write(' ' * self.indentation)
217 self.output_width = self.indentation
216 self.output_width = self.indentation
218 self.buffer_width = 0
217 self.buffer_width = 0
219 else:
218 else:
220 self.buffer.append(Breakable(sep, width, self))
219 self.buffer.append(Breakable(sep, width, self))
221 self.buffer_width += width
220 self.buffer_width += width
222 self._break_outer_groups()
221 self._break_outer_groups()
223
222
224 def break_(self):
223 def break_(self):
225 """
224 """
226 Explicitly insert a newline into the output, maintaining correct indentation.
225 Explicitly insert a newline into the output, maintaining correct indentation.
227 """
226 """
228 self.flush()
227 self.flush()
229 self.output.write(self.newline)
228 self.output.write(self.newline)
230 self.output.write(' ' * self.indentation)
229 self.output.write(' ' * self.indentation)
231 self.output_width = self.indentation
230 self.output_width = self.indentation
232 self.buffer_width = 0
231 self.buffer_width = 0
233
232
234
233
235 def begin_group(self, indent=0, open=''):
234 def begin_group(self, indent=0, open=''):
236 """
235 """
237 Begin a group. If you want support for python < 2.5 which doesn't has
236 Begin a group. If you want support for python < 2.5 which doesn't has
238 the with statement this is the preferred way:
237 the with statement this is the preferred way:
239
238
240 p.begin_group(1, '{')
239 p.begin_group(1, '{')
241 ...
240 ...
242 p.end_group(1, '}')
241 p.end_group(1, '}')
243
242
244 The python 2.5 expression would be this:
243 The python 2.5 expression would be this:
245
244
246 with p.group(1, '{', '}'):
245 with p.group(1, '{', '}'):
247 ...
246 ...
248
247
249 The first parameter specifies the indentation for the next line (usually
248 The first parameter specifies the indentation for the next line (usually
250 the width of the opening text), the second the opening text. All
249 the width of the opening text), the second the opening text. All
251 parameters are optional.
250 parameters are optional.
252 """
251 """
253 if open:
252 if open:
254 self.text(open)
253 self.text(open)
255 group = Group(self.group_stack[-1].depth + 1)
254 group = Group(self.group_stack[-1].depth + 1)
256 self.group_stack.append(group)
255 self.group_stack.append(group)
257 self.group_queue.enq(group)
256 self.group_queue.enq(group)
258 self.indentation += indent
257 self.indentation += indent
259
258
260 def _enumerate(self, seq):
259 def _enumerate(self, seq):
261 """like enumerate, but with an upper limit on the number of items"""
260 """like enumerate, but with an upper limit on the number of items"""
262 for idx, x in enumerate(seq):
261 for idx, x in enumerate(seq):
263 if self.max_seq_length and idx >= self.max_seq_length:
262 if self.max_seq_length and idx >= self.max_seq_length:
264 self.text(',')
263 self.text(',')
265 self.breakable()
264 self.breakable()
266 self.text('...')
265 self.text('...')
267 return
266 return
268 yield idx, x
267 yield idx, x
269
268
270 def end_group(self, dedent=0, close=''):
269 def end_group(self, dedent=0, close=''):
271 """End a group. See `begin_group` for more details."""
270 """End a group. See `begin_group` for more details."""
272 self.indentation -= dedent
271 self.indentation -= dedent
273 group = self.group_stack.pop()
272 group = self.group_stack.pop()
274 if not group.breakables:
273 if not group.breakables:
275 self.group_queue.remove(group)
274 self.group_queue.remove(group)
276 if close:
275 if close:
277 self.text(close)
276 self.text(close)
278
277
279 def flush(self):
278 def flush(self):
280 """Flush data that is left in the buffer."""
279 """Flush data that is left in the buffer."""
281 for data in self.buffer:
280 for data in self.buffer:
282 self.output_width += data.output(self.output, self.output_width)
281 self.output_width += data.output(self.output, self.output_width)
283 self.buffer.clear()
282 self.buffer.clear()
284 self.buffer_width = 0
283 self.buffer_width = 0
285
284
286
285
287 def _get_mro(obj_class):
286 def _get_mro(obj_class):
288 """ Get a reasonable method resolution order of a class and its superclasses
287 """ Get a reasonable method resolution order of a class and its superclasses
289 for both old-style and new-style classes.
288 for both old-style and new-style classes.
290 """
289 """
291 if not hasattr(obj_class, '__mro__'):
290 if not hasattr(obj_class, '__mro__'):
292 # Old-style class. Mix in object to make a fake new-style class.
291 # Old-style class. Mix in object to make a fake new-style class.
293 try:
292 try:
294 obj_class = type(obj_class.__name__, (obj_class, object), {})
293 obj_class = type(obj_class.__name__, (obj_class, object), {})
295 except TypeError:
294 except TypeError:
296 # Old-style extension type that does not descend from object.
295 # Old-style extension type that does not descend from object.
297 # FIXME: try to construct a more thorough MRO.
296 # FIXME: try to construct a more thorough MRO.
298 mro = [obj_class]
297 mro = [obj_class]
299 else:
298 else:
300 mro = obj_class.__mro__[1:-1]
299 mro = obj_class.__mro__[1:-1]
301 else:
300 else:
302 mro = obj_class.__mro__
301 mro = obj_class.__mro__
303 return mro
302 return mro
304
303
305
304
306 class RepresentationPrinter(PrettyPrinter):
305 class RepresentationPrinter(PrettyPrinter):
307 """
306 """
308 Special pretty printer that has a `pretty` method that calls the pretty
307 Special pretty printer that has a `pretty` method that calls the pretty
309 printer for a python object.
308 printer for a python object.
310
309
311 This class stores processing data on `self` so you must *never* use
310 This class stores processing data on `self` so you must *never* use
312 this class in a threaded environment. Always lock it or reinstanciate
311 this class in a threaded environment. Always lock it or reinstanciate
313 it.
312 it.
314
313
315 Instances also have a verbose flag callbacks can access to control their
314 Instances also have a verbose flag callbacks can access to control their
316 output. For example the default instance repr prints all attributes and
315 output. For example the default instance repr prints all attributes and
317 methods that are not prefixed by an underscore if the printer is in
316 methods that are not prefixed by an underscore if the printer is in
318 verbose mode.
317 verbose mode.
319 """
318 """
320
319
321 def __init__(self, output, verbose=False, max_width=79, newline='\n',
320 def __init__(self, output, verbose=False, max_width=79, newline='\n',
322 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
321 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
323 max_seq_length=MAX_SEQ_LENGTH):
322 max_seq_length=MAX_SEQ_LENGTH):
324
323
325 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
324 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
326 self.verbose = verbose
325 self.verbose = verbose
327 self.stack = []
326 self.stack = []
328 if singleton_pprinters is None:
327 if singleton_pprinters is None:
329 singleton_pprinters = _singleton_pprinters.copy()
328 singleton_pprinters = _singleton_pprinters.copy()
330 self.singleton_pprinters = singleton_pprinters
329 self.singleton_pprinters = singleton_pprinters
331 if type_pprinters is None:
330 if type_pprinters is None:
332 type_pprinters = _type_pprinters.copy()
331 type_pprinters = _type_pprinters.copy()
333 self.type_pprinters = type_pprinters
332 self.type_pprinters = type_pprinters
334 if deferred_pprinters is None:
333 if deferred_pprinters is None:
335 deferred_pprinters = _deferred_type_pprinters.copy()
334 deferred_pprinters = _deferred_type_pprinters.copy()
336 self.deferred_pprinters = deferred_pprinters
335 self.deferred_pprinters = deferred_pprinters
337
336
338 def pretty(self, obj):
337 def pretty(self, obj):
339 """Pretty print the given object."""
338 """Pretty print the given object."""
340 obj_id = id(obj)
339 obj_id = id(obj)
341 cycle = obj_id in self.stack
340 cycle = obj_id in self.stack
342 self.stack.append(obj_id)
341 self.stack.append(obj_id)
343 self.begin_group()
342 self.begin_group()
344 try:
343 try:
345 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
344 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
346 # First try to find registered singleton printers for the type.
345 # First try to find registered singleton printers for the type.
347 try:
346 try:
348 printer = self.singleton_pprinters[obj_id]
347 printer = self.singleton_pprinters[obj_id]
349 except (TypeError, KeyError):
348 except (TypeError, KeyError):
350 pass
349 pass
351 else:
350 else:
352 return printer(obj, self, cycle)
351 return printer(obj, self, cycle)
353 # Next walk the mro and check for either:
352 # Next walk the mro and check for either:
354 # 1) a registered printer
353 # 1) a registered printer
355 # 2) a _repr_pretty_ method
354 # 2) a _repr_pretty_ method
356 for cls in _get_mro(obj_class):
355 for cls in _get_mro(obj_class):
357 if cls in self.type_pprinters:
356 if cls in self.type_pprinters:
358 # printer registered in self.type_pprinters
357 # printer registered in self.type_pprinters
359 return self.type_pprinters[cls](obj, self, cycle)
358 return self.type_pprinters[cls](obj, self, cycle)
360 else:
359 else:
361 # deferred printer
360 # deferred printer
362 printer = self._in_deferred_types(cls)
361 printer = self._in_deferred_types(cls)
363 if printer is not None:
362 if printer is not None:
364 return printer(obj, self, cycle)
363 return printer(obj, self, cycle)
365 else:
364 else:
366 # Finally look for special method names.
365 # Finally look for special method names.
367 # Some objects automatically create any requested
366 # Some objects automatically create any requested
368 # attribute. Try to ignore most of them by checking for
367 # attribute. Try to ignore most of them by checking for
369 # callability.
368 # callability.
370 if '_repr_pretty_' in cls.__dict__:
369 if '_repr_pretty_' in cls.__dict__:
371 meth = cls._repr_pretty_
370 meth = cls._repr_pretty_
372 if callable(meth):
371 if callable(meth):
373 return meth(obj, self, cycle)
372 return meth(obj, self, cycle)
374 return _default_pprint(obj, self, cycle)
373 return _default_pprint(obj, self, cycle)
375 finally:
374 finally:
376 self.end_group()
375 self.end_group()
377 self.stack.pop()
376 self.stack.pop()
378
377
379 def _in_deferred_types(self, cls):
378 def _in_deferred_types(self, cls):
380 """
379 """
381 Check if the given class is specified in the deferred type registry.
380 Check if the given class is specified in the deferred type registry.
382
381
383 Returns the printer from the registry if it exists, and None if the
382 Returns the printer from the registry if it exists, and None if the
384 class is not in the registry. Successful matches will be moved to the
383 class is not in the registry. Successful matches will be moved to the
385 regular type registry for future use.
384 regular type registry for future use.
386 """
385 """
387 mod = _safe_getattr(cls, '__module__', None)
386 mod = _safe_getattr(cls, '__module__', None)
388 name = _safe_getattr(cls, '__name__', None)
387 name = _safe_getattr(cls, '__name__', None)
389 key = (mod, name)
388 key = (mod, name)
390 printer = None
389 printer = None
391 if key in self.deferred_pprinters:
390 if key in self.deferred_pprinters:
392 # Move the printer over to the regular registry.
391 # Move the printer over to the regular registry.
393 printer = self.deferred_pprinters.pop(key)
392 printer = self.deferred_pprinters.pop(key)
394 self.type_pprinters[cls] = printer
393 self.type_pprinters[cls] = printer
395 return printer
394 return printer
396
395
397
396
398 class Printable(object):
397 class Printable(object):
399
398
400 def output(self, stream, output_width):
399 def output(self, stream, output_width):
401 return output_width
400 return output_width
402
401
403
402
404 class Text(Printable):
403 class Text(Printable):
405
404
406 def __init__(self):
405 def __init__(self):
407 self.objs = []
406 self.objs = []
408 self.width = 0
407 self.width = 0
409
408
410 def output(self, stream, output_width):
409 def output(self, stream, output_width):
411 for obj in self.objs:
410 for obj in self.objs:
412 stream.write(obj)
411 stream.write(obj)
413 return output_width + self.width
412 return output_width + self.width
414
413
415 def add(self, obj, width):
414 def add(self, obj, width):
416 self.objs.append(obj)
415 self.objs.append(obj)
417 self.width += width
416 self.width += width
418
417
419
418
420 class Breakable(Printable):
419 class Breakable(Printable):
421
420
422 def __init__(self, seq, width, pretty):
421 def __init__(self, seq, width, pretty):
423 self.obj = seq
422 self.obj = seq
424 self.width = width
423 self.width = width
425 self.pretty = pretty
424 self.pretty = pretty
426 self.indentation = pretty.indentation
425 self.indentation = pretty.indentation
427 self.group = pretty.group_stack[-1]
426 self.group = pretty.group_stack[-1]
428 self.group.breakables.append(self)
427 self.group.breakables.append(self)
429
428
430 def output(self, stream, output_width):
429 def output(self, stream, output_width):
431 self.group.breakables.popleft()
430 self.group.breakables.popleft()
432 if self.group.want_break:
431 if self.group.want_break:
433 stream.write(self.pretty.newline)
432 stream.write(self.pretty.newline)
434 stream.write(' ' * self.indentation)
433 stream.write(' ' * self.indentation)
435 return self.indentation
434 return self.indentation
436 if not self.group.breakables:
435 if not self.group.breakables:
437 self.pretty.group_queue.remove(self.group)
436 self.pretty.group_queue.remove(self.group)
438 stream.write(self.obj)
437 stream.write(self.obj)
439 return output_width + self.width
438 return output_width + self.width
440
439
441
440
442 class Group(Printable):
441 class Group(Printable):
443
442
444 def __init__(self, depth):
443 def __init__(self, depth):
445 self.depth = depth
444 self.depth = depth
446 self.breakables = deque()
445 self.breakables = deque()
447 self.want_break = False
446 self.want_break = False
448
447
449
448
450 class GroupQueue(object):
449 class GroupQueue(object):
451
450
452 def __init__(self, *groups):
451 def __init__(self, *groups):
453 self.queue = []
452 self.queue = []
454 for group in groups:
453 for group in groups:
455 self.enq(group)
454 self.enq(group)
456
455
457 def enq(self, group):
456 def enq(self, group):
458 depth = group.depth
457 depth = group.depth
459 while depth > len(self.queue) - 1:
458 while depth > len(self.queue) - 1:
460 self.queue.append([])
459 self.queue.append([])
461 self.queue[depth].append(group)
460 self.queue[depth].append(group)
462
461
463 def deq(self):
462 def deq(self):
464 for stack in self.queue:
463 for stack in self.queue:
465 for idx, group in enumerate(reversed(stack)):
464 for idx, group in enumerate(reversed(stack)):
466 if group.breakables:
465 if group.breakables:
467 del stack[idx]
466 del stack[idx]
468 group.want_break = True
467 group.want_break = True
469 return group
468 return group
470 for group in stack:
469 for group in stack:
471 group.want_break = True
470 group.want_break = True
472 del stack[:]
471 del stack[:]
473
472
474 def remove(self, group):
473 def remove(self, group):
475 try:
474 try:
476 self.queue[group.depth].remove(group)
475 self.queue[group.depth].remove(group)
477 except ValueError:
476 except ValueError:
478 pass
477 pass
479
478
480 try:
479 try:
481 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
480 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
482 except AttributeError: # Python 3
481 except AttributeError: # Python 3
483 _baseclass_reprs = (object.__repr__,)
482 _baseclass_reprs = (object.__repr__,)
484
483
485
484
486 def _default_pprint(obj, p, cycle):
485 def _default_pprint(obj, p, cycle):
487 """
486 """
488 The default print function. Used if an object does not provide one and
487 The default print function. Used if an object does not provide one and
489 it's none of the builtin objects.
488 it's none of the builtin objects.
490 """
489 """
491 klass = _safe_getattr(obj, '__class__', None) or type(obj)
490 klass = _safe_getattr(obj, '__class__', None) or type(obj)
492 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
491 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
493 # A user-provided repr. Find newlines and replace them with p.break_()
492 # A user-provided repr. Find newlines and replace them with p.break_()
494 _repr_pprint(obj, p, cycle)
493 _repr_pprint(obj, p, cycle)
495 return
494 return
496 p.begin_group(1, '<')
495 p.begin_group(1, '<')
497 p.pretty(klass)
496 p.pretty(klass)
498 p.text(' at 0x%x' % id(obj))
497 p.text(' at 0x%x' % id(obj))
499 if cycle:
498 if cycle:
500 p.text(' ...')
499 p.text(' ...')
501 elif p.verbose:
500 elif p.verbose:
502 first = True
501 first = True
503 for key in dir(obj):
502 for key in dir(obj):
504 if not key.startswith('_'):
503 if not key.startswith('_'):
505 try:
504 try:
506 value = getattr(obj, key)
505 value = getattr(obj, key)
507 except AttributeError:
506 except AttributeError:
508 continue
507 continue
509 if isinstance(value, types.MethodType):
508 if isinstance(value, types.MethodType):
510 continue
509 continue
511 if not first:
510 if not first:
512 p.text(',')
511 p.text(',')
513 p.breakable()
512 p.breakable()
514 p.text(key)
513 p.text(key)
515 p.text('=')
514 p.text('=')
516 step = len(key) + 1
515 step = len(key) + 1
517 p.indentation += step
516 p.indentation += step
518 p.pretty(value)
517 p.pretty(value)
519 p.indentation -= step
518 p.indentation -= step
520 first = False
519 first = False
521 p.end_group(1, '>')
520 p.end_group(1, '>')
522
521
523
522
524 def _seq_pprinter_factory(start, end, basetype):
523 def _seq_pprinter_factory(start, end, basetype):
525 """
524 """
526 Factory that returns a pprint function useful for sequences. Used by
525 Factory that returns a pprint function useful for sequences. Used by
527 the default pprint for tuples, dicts, and lists.
526 the default pprint for tuples, dicts, and lists.
528 """
527 """
529 def inner(obj, p, cycle):
528 def inner(obj, p, cycle):
530 typ = type(obj)
529 typ = type(obj)
531 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
530 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
532 # If the subclass provides its own repr, use it instead.
531 # If the subclass provides its own repr, use it instead.
533 return p.text(typ.__repr__(obj))
532 return p.text(typ.__repr__(obj))
534
533
535 if cycle:
534 if cycle:
536 return p.text(start + '...' + end)
535 return p.text(start + '...' + end)
537 step = len(start)
536 step = len(start)
538 p.begin_group(step, start)
537 p.begin_group(step, start)
539 for idx, x in p._enumerate(obj):
538 for idx, x in p._enumerate(obj):
540 if idx:
539 if idx:
541 p.text(',')
540 p.text(',')
542 p.breakable()
541 p.breakable()
543 p.pretty(x)
542 p.pretty(x)
544 if len(obj) == 1 and type(obj) is tuple:
543 if len(obj) == 1 and type(obj) is tuple:
545 # Special case for 1-item tuples.
544 # Special case for 1-item tuples.
546 p.text(',')
545 p.text(',')
547 p.end_group(step, end)
546 p.end_group(step, end)
548 return inner
547 return inner
549
548
550
549
551 def _set_pprinter_factory(start, end, basetype):
550 def _set_pprinter_factory(start, end, basetype):
552 """
551 """
553 Factory that returns a pprint function useful for sets and frozensets.
552 Factory that returns a pprint function useful for sets and frozensets.
554 """
553 """
555 def inner(obj, p, cycle):
554 def inner(obj, p, cycle):
556 typ = type(obj)
555 typ = type(obj)
557 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
556 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
558 # If the subclass provides its own repr, use it instead.
557 # If the subclass provides its own repr, use it instead.
559 return p.text(typ.__repr__(obj))
558 return p.text(typ.__repr__(obj))
560
559
561 if cycle:
560 if cycle:
562 return p.text(start + '...' + end)
561 return p.text(start + '...' + end)
563 if len(obj) == 0:
562 if len(obj) == 0:
564 # Special case.
563 # Special case.
565 p.text(basetype.__name__ + '()')
564 p.text(basetype.__name__ + '()')
566 else:
565 else:
567 step = len(start)
566 step = len(start)
568 p.begin_group(step, start)
567 p.begin_group(step, start)
569 # Like dictionary keys, we will try to sort the items if there aren't too many
568 # Like dictionary keys, we will try to sort the items if there aren't too many
570 items = obj
569 items = obj
571 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
570 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
572 try:
571 try:
573 items = sorted(obj)
572 items = sorted(obj)
574 except Exception:
573 except Exception:
575 # Sometimes the items don't sort.
574 # Sometimes the items don't sort.
576 pass
575 pass
577 for idx, x in p._enumerate(items):
576 for idx, x in p._enumerate(items):
578 if idx:
577 if idx:
579 p.text(',')
578 p.text(',')
580 p.breakable()
579 p.breakable()
581 p.pretty(x)
580 p.pretty(x)
582 p.end_group(step, end)
581 p.end_group(step, end)
583 return inner
582 return inner
584
583
585
584
586 def _dict_pprinter_factory(start, end, basetype=None):
585 def _dict_pprinter_factory(start, end, basetype=None):
587 """
586 """
588 Factory that returns a pprint function used by the default pprint of
587 Factory that returns a pprint function used by the default pprint of
589 dicts and dict proxies.
588 dicts and dict proxies.
590 """
589 """
591 def inner(obj, p, cycle):
590 def inner(obj, p, cycle):
592 typ = type(obj)
591 typ = type(obj)
593 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
592 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
594 # If the subclass provides its own repr, use it instead.
593 # If the subclass provides its own repr, use it instead.
595 return p.text(typ.__repr__(obj))
594 return p.text(typ.__repr__(obj))
596
595
597 if cycle:
596 if cycle:
598 return p.text('{...}')
597 return p.text('{...}')
599 step = len(start)
598 step = len(start)
600 p.begin_group(step, start)
599 p.begin_group(step, start)
601 keys = obj.keys()
600 keys = obj.keys()
602 # if dict isn't large enough to be truncated, sort keys before displaying
601 # if dict isn't large enough to be truncated, sort keys before displaying
603 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
602 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
604 try:
603 try:
605 keys = sorted(keys)
604 keys = sorted(keys)
606 except Exception:
605 except Exception:
607 # Sometimes the keys don't sort.
606 # Sometimes the keys don't sort.
608 pass
607 pass
609 for idx, key in p._enumerate(keys):
608 for idx, key in p._enumerate(keys):
610 if idx:
609 if idx:
611 p.text(',')
610 p.text(',')
612 p.breakable()
611 p.breakable()
613 p.pretty(key)
612 p.pretty(key)
614 p.text(': ')
613 p.text(': ')
615 p.pretty(obj[key])
614 p.pretty(obj[key])
616 p.end_group(step, end)
615 p.end_group(step, end)
617 return inner
616 return inner
618
617
619
618
620 def _super_pprint(obj, p, cycle):
619 def _super_pprint(obj, p, cycle):
621 """The pprint for the super type."""
620 """The pprint for the super type."""
622 p.begin_group(8, '<super: ')
621 p.begin_group(8, '<super: ')
623 p.pretty(obj.__thisclass__)
622 p.pretty(obj.__thisclass__)
624 p.text(',')
623 p.text(',')
625 p.breakable()
624 p.breakable()
626 if PYPY: # In PyPy, super() objects don't have __self__ attributes
625 if PYPY: # In PyPy, super() objects don't have __self__ attributes
627 dself = obj.__repr__.__self__
626 dself = obj.__repr__.__self__
628 p.pretty(None if dself is obj else dself)
627 p.pretty(None if dself is obj else dself)
629 else:
628 else:
630 p.pretty(obj.__self__)
629 p.pretty(obj.__self__)
631 p.end_group(8, '>')
630 p.end_group(8, '>')
632
631
633
632
634 def _re_pattern_pprint(obj, p, cycle):
633 def _re_pattern_pprint(obj, p, cycle):
635 """The pprint function for regular expression patterns."""
634 """The pprint function for regular expression patterns."""
636 p.text('re.compile(')
635 p.text('re.compile(')
637 pattern = repr(obj.pattern)
636 pattern = repr(obj.pattern)
638 if pattern[:1] in 'uU':
637 if pattern[:1] in 'uU':
639 pattern = pattern[1:]
638 pattern = pattern[1:]
640 prefix = 'ur'
639 prefix = 'ur'
641 else:
640 else:
642 prefix = 'r'
641 prefix = 'r'
643 pattern = prefix + pattern.replace('\\\\', '\\')
642 pattern = prefix + pattern.replace('\\\\', '\\')
644 p.text(pattern)
643 p.text(pattern)
645 if obj.flags:
644 if obj.flags:
646 p.text(',')
645 p.text(',')
647 p.breakable()
646 p.breakable()
648 done_one = False
647 done_one = False
649 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
648 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
650 'UNICODE', 'VERBOSE', 'DEBUG'):
649 'UNICODE', 'VERBOSE', 'DEBUG'):
651 if obj.flags & getattr(re, flag):
650 if obj.flags & getattr(re, flag):
652 if done_one:
651 if done_one:
653 p.text('|')
652 p.text('|')
654 p.text('re.' + flag)
653 p.text('re.' + flag)
655 done_one = True
654 done_one = True
656 p.text(')')
655 p.text(')')
657
656
658
657
659 def _type_pprint(obj, p, cycle):
658 def _type_pprint(obj, p, cycle):
660 """The pprint for classes and types."""
659 """The pprint for classes and types."""
661 # Heap allocated types might not have the module attribute,
660 # Heap allocated types might not have the module attribute,
662 # and others may set it to None.
661 # and others may set it to None.
663
662
664 # Checks for a __repr__ override in the metaclass. Can't compare the
663 # Checks for a __repr__ override in the metaclass. Can't compare the
665 # type(obj).__repr__ directly because in PyPy the representation function
664 # type(obj).__repr__ directly because in PyPy the representation function
666 # inherited from type isn't the same type.__repr__
665 # inherited from type isn't the same type.__repr__
667 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
666 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
668 _repr_pprint(obj, p, cycle)
667 _repr_pprint(obj, p, cycle)
669 return
668 return
670
669
671 mod = _safe_getattr(obj, '__module__', None)
670 mod = _safe_getattr(obj, '__module__', None)
672 try:
671 try:
673 name = obj.__qualname__
672 name = obj.__qualname__
674 if not isinstance(name, str):
673 if not isinstance(name, str):
675 # This can happen if the type implements __qualname__ as a property
674 # This can happen if the type implements __qualname__ as a property
676 # or other descriptor in Python 2.
675 # or other descriptor in Python 2.
677 raise Exception("Try __name__")
676 raise Exception("Try __name__")
678 except Exception:
677 except Exception:
679 name = obj.__name__
678 name = obj.__name__
680 if not isinstance(name, str):
679 if not isinstance(name, str):
681 name = '<unknown type>'
680 name = '<unknown type>'
682
681
683 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
682 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
684 p.text(name)
683 p.text(name)
685 else:
684 else:
686 p.text(mod + '.' + name)
685 p.text(mod + '.' + name)
687
686
688
687
689 def _repr_pprint(obj, p, cycle):
688 def _repr_pprint(obj, p, cycle):
690 """A pprint that just redirects to the normal repr function."""
689 """A pprint that just redirects to the normal repr function."""
691 # Find newlines and replace them with p.break_()
690 # Find newlines and replace them with p.break_()
692 output = repr(obj)
691 output = repr(obj)
693 for idx,output_line in enumerate(output.splitlines()):
692 for idx,output_line in enumerate(output.splitlines()):
694 if idx:
693 if idx:
695 p.break_()
694 p.break_()
696 p.text(output_line)
695 p.text(output_line)
697
696
698
697
699 def _function_pprint(obj, p, cycle):
698 def _function_pprint(obj, p, cycle):
700 """Base pprint for all functions and builtin functions."""
699 """Base pprint for all functions and builtin functions."""
701 name = _safe_getattr(obj, '__qualname__', obj.__name__)
700 name = _safe_getattr(obj, '__qualname__', obj.__name__)
702 mod = obj.__module__
701 mod = obj.__module__
703 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
702 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
704 name = mod + '.' + name
703 name = mod + '.' + name
705 p.text('<function %s>' % name)
704 p.text('<function %s>' % name)
706
705
707
706
708 def _exception_pprint(obj, p, cycle):
707 def _exception_pprint(obj, p, cycle):
709 """Base pprint for all exceptions."""
708 """Base pprint for all exceptions."""
710 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
709 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
711 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
710 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
712 name = '%s.%s' % (obj.__class__.__module__, name)
711 name = '%s.%s' % (obj.__class__.__module__, name)
713 step = len(name) + 1
712 step = len(name) + 1
714 p.begin_group(step, name + '(')
713 p.begin_group(step, name + '(')
715 for idx, arg in enumerate(getattr(obj, 'args', ())):
714 for idx, arg in enumerate(getattr(obj, 'args', ())):
716 if idx:
715 if idx:
717 p.text(',')
716 p.text(',')
718 p.breakable()
717 p.breakable()
719 p.pretty(arg)
718 p.pretty(arg)
720 p.end_group(step, ')')
719 p.end_group(step, ')')
721
720
722
721
723 #: the exception base
722 #: the exception base
724 try:
723 try:
725 _exception_base = BaseException
724 _exception_base = BaseException
726 except NameError:
725 except NameError:
727 _exception_base = Exception
726 _exception_base = Exception
728
727
729
728
730 #: printers for builtin types
729 #: printers for builtin types
731 _type_pprinters = {
730 _type_pprinters = {
732 int: _repr_pprint,
731 int: _repr_pprint,
733 float: _repr_pprint,
732 float: _repr_pprint,
734 str: _repr_pprint,
733 str: _repr_pprint,
735 tuple: _seq_pprinter_factory('(', ')', tuple),
734 tuple: _seq_pprinter_factory('(', ')', tuple),
736 list: _seq_pprinter_factory('[', ']', list),
735 list: _seq_pprinter_factory('[', ']', list),
737 dict: _dict_pprinter_factory('{', '}', dict),
736 dict: _dict_pprinter_factory('{', '}', dict),
738
737
739 set: _set_pprinter_factory('{', '}', set),
738 set: _set_pprinter_factory('{', '}', set),
740 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
739 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
741 super: _super_pprint,
740 super: _super_pprint,
742 _re_pattern_type: _re_pattern_pprint,
741 _re_pattern_type: _re_pattern_pprint,
743 type: _type_pprint,
742 type: _type_pprint,
744 types.FunctionType: _function_pprint,
743 types.FunctionType: _function_pprint,
745 types.BuiltinFunctionType: _function_pprint,
744 types.BuiltinFunctionType: _function_pprint,
746 types.MethodType: _repr_pprint,
745 types.MethodType: _repr_pprint,
747
746
748 datetime.datetime: _repr_pprint,
747 datetime.datetime: _repr_pprint,
749 datetime.timedelta: _repr_pprint,
748 datetime.timedelta: _repr_pprint,
750 _exception_base: _exception_pprint
749 _exception_base: _exception_pprint
751 }
750 }
752
751
753 try:
752 try:
754 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
753 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
755 # using dict.setdefault avoids overwritting the dict printer
754 # using dict.setdefault avoids overwritting the dict printer
756 _type_pprinters.setdefault(types.DictProxyType,
755 _type_pprinters.setdefault(types.DictProxyType,
757 _dict_pprinter_factory('dict_proxy({', '})'))
756 _dict_pprinter_factory('dict_proxy({', '})'))
758 _type_pprinters[types.ClassType] = _type_pprint
757 _type_pprinters[types.ClassType] = _type_pprint
759 _type_pprinters[types.SliceType] = _repr_pprint
758 _type_pprinters[types.SliceType] = _repr_pprint
760 except AttributeError: # Python 3
759 except AttributeError: # Python 3
761 _type_pprinters[types.MappingProxyType] = \
760 _type_pprinters[types.MappingProxyType] = \
762 _dict_pprinter_factory('mappingproxy({', '})')
761 _dict_pprinter_factory('mappingproxy({', '})')
763 _type_pprinters[slice] = _repr_pprint
762 _type_pprinters[slice] = _repr_pprint
764
763
765 try:
764 try:
766 _type_pprinters[long] = _repr_pprint
765 _type_pprinters[long] = _repr_pprint
767 _type_pprinters[unicode] = _repr_pprint
766 _type_pprinters[unicode] = _repr_pprint
768 except NameError:
767 except NameError:
769 _type_pprinters[range] = _repr_pprint
768 _type_pprinters[range] = _repr_pprint
770 _type_pprinters[bytes] = _repr_pprint
769 _type_pprinters[bytes] = _repr_pprint
771
770
772 #: printers for types specified by name
771 #: printers for types specified by name
773 _deferred_type_pprinters = {
772 _deferred_type_pprinters = {
774 }
773 }
775
774
776 def for_type(typ, func):
775 def for_type(typ, func):
777 """
776 """
778 Add a pretty printer for a given type.
777 Add a pretty printer for a given type.
779 """
778 """
780 oldfunc = _type_pprinters.get(typ, None)
779 oldfunc = _type_pprinters.get(typ, None)
781 if func is not None:
780 if func is not None:
782 # To support easy restoration of old pprinters, we need to ignore Nones.
781 # To support easy restoration of old pprinters, we need to ignore Nones.
783 _type_pprinters[typ] = func
782 _type_pprinters[typ] = func
784 return oldfunc
783 return oldfunc
785
784
786 def for_type_by_name(type_module, type_name, func):
785 def for_type_by_name(type_module, type_name, func):
787 """
786 """
788 Add a pretty printer for a type specified by the module and name of a type
787 Add a pretty printer for a type specified by the module and name of a type
789 rather than the type object itself.
788 rather than the type object itself.
790 """
789 """
791 key = (type_module, type_name)
790 key = (type_module, type_name)
792 oldfunc = _deferred_type_pprinters.get(key, None)
791 oldfunc = _deferred_type_pprinters.get(key, None)
793 if func is not None:
792 if func is not None:
794 # To support easy restoration of old pprinters, we need to ignore Nones.
793 # To support easy restoration of old pprinters, we need to ignore Nones.
795 _deferred_type_pprinters[key] = func
794 _deferred_type_pprinters[key] = func
796 return oldfunc
795 return oldfunc
797
796
798
797
799 #: printers for the default singletons
798 #: printers for the default singletons
800 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
799 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
801 NotImplemented]), _repr_pprint)
800 NotImplemented]), _repr_pprint)
802
801
803
802
804 def _defaultdict_pprint(obj, p, cycle):
803 def _defaultdict_pprint(obj, p, cycle):
805 name = obj.__class__.__name__
804 name = obj.__class__.__name__
806 with p.group(len(name) + 1, name + '(', ')'):
805 with p.group(len(name) + 1, name + '(', ')'):
807 if cycle:
806 if cycle:
808 p.text('...')
807 p.text('...')
809 else:
808 else:
810 p.pretty(obj.default_factory)
809 p.pretty(obj.default_factory)
811 p.text(',')
810 p.text(',')
812 p.breakable()
811 p.breakable()
813 p.pretty(dict(obj))
812 p.pretty(dict(obj))
814
813
815 def _ordereddict_pprint(obj, p, cycle):
814 def _ordereddict_pprint(obj, p, cycle):
816 name = obj.__class__.__name__
815 name = obj.__class__.__name__
817 with p.group(len(name) + 1, name + '(', ')'):
816 with p.group(len(name) + 1, name + '(', ')'):
818 if cycle:
817 if cycle:
819 p.text('...')
818 p.text('...')
820 elif len(obj):
819 elif len(obj):
821 p.pretty(list(obj.items()))
820 p.pretty(list(obj.items()))
822
821
823 def _deque_pprint(obj, p, cycle):
822 def _deque_pprint(obj, p, cycle):
824 name = obj.__class__.__name__
823 name = obj.__class__.__name__
825 with p.group(len(name) + 1, name + '(', ')'):
824 with p.group(len(name) + 1, name + '(', ')'):
826 if cycle:
825 if cycle:
827 p.text('...')
826 p.text('...')
828 else:
827 else:
829 p.pretty(list(obj))
828 p.pretty(list(obj))
830
829
831
830
832 def _counter_pprint(obj, p, cycle):
831 def _counter_pprint(obj, p, cycle):
833 name = obj.__class__.__name__
832 name = obj.__class__.__name__
834 with p.group(len(name) + 1, name + '(', ')'):
833 with p.group(len(name) + 1, name + '(', ')'):
835 if cycle:
834 if cycle:
836 p.text('...')
835 p.text('...')
837 elif len(obj):
836 elif len(obj):
838 p.pretty(dict(obj))
837 p.pretty(dict(obj))
839
838
840 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
839 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
841 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
840 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
842 for_type_by_name('collections', 'deque', _deque_pprint)
841 for_type_by_name('collections', 'deque', _deque_pprint)
843 for_type_by_name('collections', 'Counter', _counter_pprint)
842 for_type_by_name('collections', 'Counter', _counter_pprint)
844
843
845 if __name__ == '__main__':
844 if __name__ == '__main__':
846 from random import randrange
845 from random import randrange
847 class Foo(object):
846 class Foo(object):
848 def __init__(self):
847 def __init__(self):
849 self.foo = 1
848 self.foo = 1
850 self.bar = re.compile(r'\s+')
849 self.bar = re.compile(r'\s+')
851 self.blub = dict.fromkeys(range(30), randrange(1, 40))
850 self.blub = dict.fromkeys(range(30), randrange(1, 40))
852 self.hehe = 23424.234234
851 self.hehe = 23424.234234
853 self.list = ["blub", "blah", self]
852 self.list = ["blub", "blah", self]
854
853
855 def get_foo(self):
854 def get_foo(self):
856 print("foo")
855 print("foo")
857
856
858 pprint(Foo(), verbose=True)
857 pprint(Foo(), verbose=True)
General Comments 0
You need to be logged in to leave comments. Login now