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