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