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