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