Show More
@@ -1,279 +1,282 | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Displayhook for IPython. |
|
2 | """Displayhook for IPython. | |
3 |
|
3 | |||
4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
4 | This defines a callable class that IPython uses for `sys.displayhook`. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Fernando Perez |
|
8 | * Fernando Perez | |
9 | * Brian Granger |
|
9 | * Brian Granger | |
10 | * Robert Kern |
|
10 | * Robert Kern | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Copyright (C) 2008-2011 The IPython Development Team |
|
14 | # Copyright (C) 2008-2011 The IPython Development Team | |
15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
16 | # |
|
16 | # | |
17 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | # Distributed under the terms of the BSD License. The full license is in | |
18 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 | # Imports |
|
22 | # Imports | |
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 | from __future__ import print_function |
|
24 | from __future__ import print_function | |
25 |
|
25 | |||
26 | import sys |
|
26 | import sys | |
27 |
|
27 | |||
28 |
|
28 | |||
29 | from IPython.config.configurable import Configurable |
|
29 | from IPython.config.configurable import Configurable | |
30 | from IPython.utils import io |
|
30 | from IPython.utils import io | |
31 | from IPython.utils.py3compat import builtin_mod |
|
31 | from IPython.utils.py3compat import builtin_mod | |
32 | from IPython.utils.traitlets import Instance |
|
32 | from IPython.utils.traitlets import Instance | |
33 | from IPython.utils.warn import warn |
|
33 | from IPython.utils.warn import warn | |
34 |
|
34 | |||
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 | # Main displayhook class |
|
36 | # Main displayhook class | |
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 |
|
38 | |||
39 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
39 | # TODO: Move the various attributes (cache_size, [others now moved]). Some | |
40 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
40 | # of these are also attributes of InteractiveShell. They should be on ONE object | |
41 | # only and the other objects should ask that one object for their values. |
|
41 | # only and the other objects should ask that one object for their values. | |
42 |
|
42 | |||
43 | class DisplayHook(Configurable): |
|
43 | class DisplayHook(Configurable): | |
44 | """The custom IPython displayhook to replace sys.displayhook. |
|
44 | """The custom IPython displayhook to replace sys.displayhook. | |
45 |
|
45 | |||
46 | This class does many things, but the basic idea is that it is a callable |
|
46 | This class does many things, but the basic idea is that it is a callable | |
47 | that gets called anytime user code returns a value. |
|
47 | that gets called anytime user code returns a value. | |
48 | """ |
|
48 | """ | |
49 |
|
49 | |||
50 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
50 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
51 |
|
51 | |||
52 | def __init__(self, shell=None, cache_size=1000, **kwargs): |
|
52 | def __init__(self, shell=None, cache_size=1000, **kwargs): | |
53 | super(DisplayHook, self).__init__(shell=shell, **kwargs) |
|
53 | super(DisplayHook, self).__init__(shell=shell, **kwargs) | |
54 |
|
54 | |||
55 | cache_size_min = 3 |
|
55 | cache_size_min = 3 | |
56 | if cache_size <= 0: |
|
56 | if cache_size <= 0: | |
57 | self.do_full_cache = 0 |
|
57 | self.do_full_cache = 0 | |
58 | cache_size = 0 |
|
58 | cache_size = 0 | |
59 | elif cache_size < cache_size_min: |
|
59 | elif cache_size < cache_size_min: | |
60 | self.do_full_cache = 0 |
|
60 | self.do_full_cache = 0 | |
61 | cache_size = 0 |
|
61 | cache_size = 0 | |
62 | warn('caching was disabled (min value for cache size is %s).' % |
|
62 | warn('caching was disabled (min value for cache size is %s).' % | |
63 | cache_size_min,level=3) |
|
63 | cache_size_min,level=3) | |
64 | else: |
|
64 | else: | |
65 | self.do_full_cache = 1 |
|
65 | self.do_full_cache = 1 | |
66 |
|
66 | |||
67 | self.cache_size = cache_size |
|
67 | self.cache_size = cache_size | |
68 |
|
68 | |||
69 | # we need a reference to the user-level namespace |
|
69 | # we need a reference to the user-level namespace | |
70 | self.shell = shell |
|
70 | self.shell = shell | |
71 |
|
71 | |||
72 | self._,self.__,self.___ = '','','' |
|
72 | self._,self.__,self.___ = '','','' | |
73 |
|
73 | |||
74 | # these are deliberately global: |
|
74 | # these are deliberately global: | |
75 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
75 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
76 | self.shell.user_ns.update(to_user_ns) |
|
76 | self.shell.user_ns.update(to_user_ns) | |
77 |
|
77 | |||
78 | @property |
|
78 | @property | |
79 | def prompt_count(self): |
|
79 | def prompt_count(self): | |
80 | return self.shell.execution_count |
|
80 | return self.shell.execution_count | |
81 |
|
81 | |||
82 | #------------------------------------------------------------------------- |
|
82 | #------------------------------------------------------------------------- | |
83 | # Methods used in __call__. Override these methods to modify the behavior |
|
83 | # Methods used in __call__. Override these methods to modify the behavior | |
84 | # of the displayhook. |
|
84 | # of the displayhook. | |
85 | #------------------------------------------------------------------------- |
|
85 | #------------------------------------------------------------------------- | |
86 |
|
86 | |||
87 | def check_for_underscore(self): |
|
87 | def check_for_underscore(self): | |
88 | """Check if the user has set the '_' variable by hand.""" |
|
88 | """Check if the user has set the '_' variable by hand.""" | |
89 | # If something injected a '_' variable in __builtin__, delete |
|
89 | # If something injected a '_' variable in __builtin__, delete | |
90 | # ipython's automatic one so we don't clobber that. gettext() in |
|
90 | # ipython's automatic one so we don't clobber that. gettext() in | |
91 | # particular uses _, so we need to stay away from it. |
|
91 | # particular uses _, so we need to stay away from it. | |
92 | if '_' in builtin_mod.__dict__: |
|
92 | if '_' in builtin_mod.__dict__: | |
93 | try: |
|
93 | try: | |
94 | del self.shell.user_ns['_'] |
|
94 | del self.shell.user_ns['_'] | |
95 | except KeyError: |
|
95 | except KeyError: | |
96 | pass |
|
96 | pass | |
97 |
|
97 | |||
98 | def quiet(self): |
|
98 | def quiet(self): | |
99 | """Should we silence the display hook because of ';'?""" |
|
99 | """Should we silence the display hook because of ';'?""" | |
100 | # do not print output if input ends in ';' |
|
100 | # do not print output if input ends in ';' | |
101 | try: |
|
101 | try: | |
102 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] |
|
102 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] | |
103 | if cell.rstrip().endswith(';'): |
|
103 | if cell.rstrip().endswith(';'): | |
104 | return True |
|
104 | return True | |
105 | except IndexError: |
|
105 | except IndexError: | |
106 | # some uses of ipshellembed may fail here |
|
106 | # some uses of ipshellembed may fail here | |
107 | pass |
|
107 | pass | |
108 | return False |
|
108 | return False | |
109 |
|
109 | |||
110 | def start_displayhook(self): |
|
110 | def start_displayhook(self): | |
111 | """Start the displayhook, initializing resources.""" |
|
111 | """Start the displayhook, initializing resources.""" | |
112 | pass |
|
112 | pass | |
113 |
|
113 | |||
114 | def write_output_prompt(self): |
|
114 | def write_output_prompt(self): | |
115 | """Write the output prompt. |
|
115 | """Write the output prompt. | |
116 |
|
116 | |||
117 | The default implementation simply writes the prompt to |
|
117 | The default implementation simply writes the prompt to | |
118 | ``io.stdout``. |
|
118 | ``io.stdout``. | |
119 | """ |
|
119 | """ | |
120 | # Use write, not print which adds an extra space. |
|
120 | # Use write, not print which adds an extra space. | |
121 | io.stdout.write(self.shell.separate_out) |
|
121 | io.stdout.write(self.shell.separate_out) | |
122 | outprompt = self.shell.prompt_manager.render('out') |
|
122 | outprompt = self.shell.prompt_manager.render('out') | |
123 | if self.do_full_cache: |
|
123 | if self.do_full_cache: | |
124 | io.stdout.write(outprompt) |
|
124 | io.stdout.write(outprompt) | |
125 |
|
125 | |||
126 | def compute_format_data(self, result): |
|
126 | def compute_format_data(self, result): | |
127 | """Compute format data of the object to be displayed. |
|
127 | """Compute format data of the object to be displayed. | |
128 |
|
128 | |||
129 | The format data is a generalization of the :func:`repr` of an object. |
|
129 | The format data is a generalization of the :func:`repr` of an object. | |
130 | In the default implementation the format data is a :class:`dict` of |
|
130 | In the default implementation the format data is a :class:`dict` of | |
131 | key value pair where the keys are valid MIME types and the values |
|
131 | key value pair where the keys are valid MIME types and the values | |
132 | are JSON'able data structure containing the raw data for that MIME |
|
132 | are JSON'able data structure containing the raw data for that MIME | |
133 | type. It is up to frontends to determine pick a MIME to to use and |
|
133 | type. It is up to frontends to determine pick a MIME to to use and | |
134 | display that data in an appropriate manner. |
|
134 | display that data in an appropriate manner. | |
135 |
|
135 | |||
136 | This method only computes the format data for the object and should |
|
136 | This method only computes the format data for the object and should | |
137 | NOT actually print or write that to a stream. |
|
137 | NOT actually print or write that to a stream. | |
138 |
|
138 | |||
139 | Parameters |
|
139 | Parameters | |
140 | ---------- |
|
140 | ---------- | |
141 | result : object |
|
141 | result : object | |
142 | The Python object passed to the display hook, whose format will be |
|
142 | The Python object passed to the display hook, whose format will be | |
143 | computed. |
|
143 | computed. | |
144 |
|
144 | |||
145 | Returns |
|
145 | Returns | |
146 | ------- |
|
146 | ------- | |
147 | (format_dict, md_dict) : dict |
|
147 | (format_dict, md_dict) : dict | |
148 | format_dict is a :class:`dict` whose keys are valid MIME types and values are |
|
148 | format_dict is a :class:`dict` whose keys are valid MIME types and values are | |
149 | JSON'able raw data for that MIME type. It is recommended that |
|
149 | JSON'able raw data for that MIME type. It is recommended that | |
150 | all return values of this should always include the "text/plain" |
|
150 | all return values of this should always include the "text/plain" | |
151 | MIME type representation of the object. |
|
151 | MIME type representation of the object. | |
152 | md_dict is a :class:`dict` with the same MIME type keys |
|
152 | md_dict is a :class:`dict` with the same MIME type keys | |
153 | of metadata associated with each output. |
|
153 | of metadata associated with each output. | |
154 |
|
154 | |||
155 | """ |
|
155 | """ | |
156 | return self.shell.display_formatter.format(result) |
|
156 | return self.shell.display_formatter.format(result) | |
157 |
|
157 | |||
158 | def write_format_data(self, format_dict, md_dict=None): |
|
158 | def write_format_data(self, format_dict, md_dict=None): | |
159 | """Write the format data dict to the frontend. |
|
159 | """Write the format data dict to the frontend. | |
160 |
|
160 | |||
161 | This default version of this method simply writes the plain text |
|
161 | This default version of this method simply writes the plain text | |
162 | representation of the object to ``io.stdout``. Subclasses should |
|
162 | representation of the object to ``io.stdout``. Subclasses should | |
163 | override this method to send the entire `format_dict` to the |
|
163 | override this method to send the entire `format_dict` to the | |
164 | frontends. |
|
164 | frontends. | |
165 |
|
165 | |||
166 | Parameters |
|
166 | Parameters | |
167 | ---------- |
|
167 | ---------- | |
168 | format_dict : dict |
|
168 | format_dict : dict | |
169 | The format dict for the object passed to `sys.displayhook`. |
|
169 | The format dict for the object passed to `sys.displayhook`. | |
170 | md_dict : dict (optional) |
|
170 | md_dict : dict (optional) | |
171 | The metadata dict to be associated with the display data. |
|
171 | The metadata dict to be associated with the display data. | |
172 | """ |
|
172 | """ | |
173 | # We want to print because we want to always make sure we have a |
|
173 | # We want to print because we want to always make sure we have a | |
174 | # newline, even if all the prompt separators are ''. This is the |
|
174 | # newline, even if all the prompt separators are ''. This is the | |
175 | # standard IPython behavior. |
|
175 | # standard IPython behavior. | |
176 | result_repr = format_dict['text/plain'] |
|
176 | result_repr = format_dict['text/plain'] | |
177 | if '\n' in result_repr: |
|
177 | if '\n' in result_repr: | |
178 | # So that multi-line strings line up with the left column of |
|
178 | # So that multi-line strings line up with the left column of | |
179 | # the screen, instead of having the output prompt mess up |
|
179 | # the screen, instead of having the output prompt mess up | |
180 | # their first line. |
|
180 | # their first line. | |
181 | # We use the prompt template instead of the expanded prompt |
|
181 | # We use the prompt template instead of the expanded prompt | |
182 | # because the expansion may add ANSI escapes that will interfere |
|
182 | # because the expansion may add ANSI escapes that will interfere | |
183 | # with our ability to determine whether or not we should add |
|
183 | # with our ability to determine whether or not we should add | |
184 | # a newline. |
|
184 | # a newline. | |
185 | prompt_template = self.shell.prompt_manager.out_template |
|
185 | prompt_template = self.shell.prompt_manager.out_template | |
186 | if prompt_template and not prompt_template.endswith('\n'): |
|
186 | if prompt_template and not prompt_template.endswith('\n'): | |
187 | # But avoid extraneous empty lines. |
|
187 | # But avoid extraneous empty lines. | |
188 | result_repr = '\n' + result_repr |
|
188 | result_repr = '\n' + result_repr | |
189 |
|
189 | |||
190 | print(result_repr, file=io.stdout) |
|
190 | print(result_repr, file=io.stdout) | |
191 |
|
191 | |||
192 | def update_user_ns(self, result): |
|
192 | def update_user_ns(self, result): | |
193 | """Update user_ns with various things like _, __, _1, etc.""" |
|
193 | """Update user_ns with various things like _, __, _1, etc.""" | |
194 |
|
194 | |||
195 | # Avoid recursive reference when displaying _oh/Out |
|
195 | # Avoid recursive reference when displaying _oh/Out | |
196 | if result is not self.shell.user_ns['_oh']: |
|
196 | if result is not self.shell.user_ns['_oh']: | |
197 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
197 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: | |
198 | warn('Output cache limit (currently '+ |
|
198 | warn('Output cache limit (currently '+ | |
199 | repr(self.cache_size)+' entries) hit.\n' |
|
199 | repr(self.cache_size)+' entries) hit.\n' | |
200 | 'Flushing cache and resetting history counter...\n' |
|
200 | 'Flushing cache and resetting history counter...\n' | |
201 | 'The only history variables available will be _,__,___ and _1\n' |
|
201 | 'The only history variables available will be _,__,___ and _1\n' | |
202 | 'with the current result.') |
|
202 | 'with the current result.') | |
203 |
|
203 | |||
204 | self.flush() |
|
204 | self.flush() | |
205 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
205 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
206 | # we cause buggy behavior for things like gettext). |
|
206 | # we cause buggy behavior for things like gettext). | |
207 |
|
207 | |||
208 | if '_' not in builtin_mod.__dict__: |
|
208 | if '_' not in builtin_mod.__dict__: | |
209 | self.___ = self.__ |
|
209 | self.___ = self.__ | |
210 | self.__ = self._ |
|
210 | self.__ = self._ | |
211 | self._ = result |
|
211 | self._ = result | |
212 | self.shell.push({'_':self._, |
|
212 | self.shell.push({'_':self._, | |
213 | '__':self.__, |
|
213 | '__':self.__, | |
214 | '___':self.___}, interactive=False) |
|
214 | '___':self.___}, interactive=False) | |
215 |
|
215 | |||
216 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
216 | # hackish access to top-level namespace to create _1,_2... dynamically | |
217 | to_main = {} |
|
217 | to_main = {} | |
218 | if self.do_full_cache: |
|
218 | if self.do_full_cache: | |
219 | new_result = '_'+repr(self.prompt_count) |
|
219 | new_result = '_'+repr(self.prompt_count) | |
220 | to_main[new_result] = result |
|
220 | to_main[new_result] = result | |
221 | self.shell.push(to_main, interactive=False) |
|
221 | self.shell.push(to_main, interactive=False) | |
222 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
222 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
223 |
|
223 | |||
224 | def log_output(self, format_dict): |
|
224 | def log_output(self, format_dict): | |
225 | """Log the output.""" |
|
225 | """Log the output.""" | |
226 | if self.shell.logger.log_output: |
|
226 | if self.shell.logger.log_output: | |
227 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
227 | self.shell.logger.log_write(format_dict['text/plain'], 'output') | |
228 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
228 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ | |
229 | format_dict['text/plain'] |
|
229 | format_dict['text/plain'] | |
230 |
|
230 | |||
231 | def finish_displayhook(self): |
|
231 | def finish_displayhook(self): | |
232 | """Finish up all displayhook activities.""" |
|
232 | """Finish up all displayhook activities.""" | |
233 | io.stdout.write(self.shell.separate_out2) |
|
233 | io.stdout.write(self.shell.separate_out2) | |
234 | io.stdout.flush() |
|
234 | io.stdout.flush() | |
235 |
|
235 | |||
236 | def __call__(self, result=None): |
|
236 | def __call__(self, result=None): | |
237 | """Printing with history cache management. |
|
237 | """Printing with history cache management. | |
238 |
|
238 | |||
239 | This is invoked everytime the interpreter needs to print, and is |
|
239 | This is invoked everytime the interpreter needs to print, and is | |
240 | activated by setting the variable sys.displayhook to it. |
|
240 | activated by setting the variable sys.displayhook to it. | |
241 | """ |
|
241 | """ | |
242 | self.check_for_underscore() |
|
242 | self.check_for_underscore() | |
243 | if result is not None and not self.quiet(): |
|
243 | if result is not None and not self.quiet(): | |
244 | self.start_displayhook() |
|
244 | # If _ipython_display_ is defined, use that to display this object. If | |
245 | self.write_output_prompt() |
|
245 | # it returns NotImplemented, use the _repr_ logic (default). | |
246 | format_dict, md_dict = self.compute_format_data(result) |
|
246 | if not hasattr(result, '_ipython_display_') or result._ipython_display_() == NotImplemented: | |
247 | self.write_format_data(format_dict, md_dict) |
|
247 | self.start_displayhook() | |
248 | self.update_user_ns(result) |
|
248 | self.write_output_prompt() | |
249 | self.log_output(format_dict) |
|
249 | format_dict, md_dict = self.compute_format_data(result) | |
250 | self.finish_displayhook() |
|
250 | self.write_format_data(format_dict, md_dict) | |
|
251 | self.update_user_ns(result) | |||
|
252 | self.log_output(format_dict) | |||
|
253 | self.finish_displayhook() | |||
251 |
|
254 | |||
252 | def flush(self): |
|
255 | def flush(self): | |
253 | if not self.do_full_cache: |
|
256 | if not self.do_full_cache: | |
254 | raise ValueError("You shouldn't have reached the cache flush " |
|
257 | raise ValueError("You shouldn't have reached the cache flush " | |
255 | "if full caching is not enabled!") |
|
258 | "if full caching is not enabled!") | |
256 | # delete auto-generated vars from global namespace |
|
259 | # delete auto-generated vars from global namespace | |
257 |
|
260 | |||
258 | for n in range(1,self.prompt_count + 1): |
|
261 | for n in range(1,self.prompt_count + 1): | |
259 | key = '_'+repr(n) |
|
262 | key = '_'+repr(n) | |
260 | try: |
|
263 | try: | |
261 | del self.shell.user_ns[key] |
|
264 | del self.shell.user_ns[key] | |
262 | except: pass |
|
265 | except: pass | |
263 | # In some embedded circumstances, the user_ns doesn't have the |
|
266 | # In some embedded circumstances, the user_ns doesn't have the | |
264 | # '_oh' key set up. |
|
267 | # '_oh' key set up. | |
265 | oh = self.shell.user_ns.get('_oh', None) |
|
268 | oh = self.shell.user_ns.get('_oh', None) | |
266 | if oh is not None: |
|
269 | if oh is not None: | |
267 | oh.clear() |
|
270 | oh.clear() | |
268 |
|
271 | |||
269 | # Release our own references to objects: |
|
272 | # Release our own references to objects: | |
270 | self._, self.__, self.___ = '', '', '' |
|
273 | self._, self.__, self.___ = '', '', '' | |
271 |
|
274 | |||
272 | if '_' not in builtin_mod.__dict__: |
|
275 | if '_' not in builtin_mod.__dict__: | |
273 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
276 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
274 | import gc |
|
277 | import gc | |
275 | # TODO: Is this really needed? |
|
278 | # TODO: Is this really needed? | |
276 | # IronPython blocks here forever |
|
279 | # IronPython blocks here forever | |
277 | if sys.platform != "cli": |
|
280 | if sys.platform != "cli": | |
278 | gc.collect() |
|
281 | gc.collect() | |
279 |
|
282 |
@@ -1,819 +1,816 | |||||
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 sys |
|
28 | import sys | |
29 | import warnings |
|
29 | import warnings | |
30 |
|
30 | |||
31 | from IPython.external.decorator import decorator |
|
31 | from IPython.external.decorator import decorator | |
32 |
|
32 | |||
33 | # Our own imports |
|
33 | # Our own imports | |
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.lib import pretty |
|
35 | from IPython.lib import pretty | |
36 | from IPython.utils import io |
|
36 | from IPython.utils import io | |
37 | from IPython.utils.traitlets import ( |
|
37 | from IPython.utils.traitlets import ( | |
38 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
38 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, | |
39 | ) |
|
39 | ) | |
40 | from IPython.utils.warn import warn |
|
40 | from IPython.utils.warn import warn | |
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 | class DisplayFormatter(Configurable): |
|
55 | class DisplayFormatter(Configurable): | |
56 |
|
56 | |||
57 | # When set to true only the default plain text formatter will be used. |
|
57 | # When set to true only the default plain text formatter will be used. | |
58 | plain_text_only = Bool(False, config=True) |
|
58 | plain_text_only = Bool(False, config=True) | |
59 | def _plain_text_only_changed(self, name, old, new): |
|
59 | def _plain_text_only_changed(self, name, old, new): | |
60 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
60 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. | |
61 |
|
61 | |||
62 | Use DisplayFormatter.active_types = ['text/plain'] |
|
62 | Use DisplayFormatter.active_types = ['text/plain'] | |
63 | for the same effect. |
|
63 | for the same effect. | |
64 | """, DeprecationWarning) |
|
64 | """, DeprecationWarning) | |
65 | if new: |
|
65 | if new: | |
66 | self.active_types = ['text/plain'] |
|
66 | self.active_types = ['text/plain'] | |
67 | else: |
|
67 | else: | |
68 | self.active_types = self.format_types |
|
68 | self.active_types = self.format_types | |
69 |
|
69 | |||
70 | active_types = List(Unicode, config=True, |
|
70 | active_types = List(Unicode, config=True, | |
71 | help="""List of currently active mime-types to display. |
|
71 | help="""List of currently active mime-types to display. | |
72 | You can use this to set a white-list for formats to display. |
|
72 | You can use this to set a white-list for formats to display. | |
73 |
|
73 | |||
74 | Most users will not need to change this value. |
|
74 | Most users will not need to change this value. | |
75 | """) |
|
75 | """) | |
76 | def _active_types_default(self): |
|
76 | def _active_types_default(self): | |
77 | return self.format_types |
|
77 | return self.format_types | |
78 |
|
78 | |||
79 | def _active_types_changed(self, name, old, new): |
|
79 | def _active_types_changed(self, name, old, new): | |
80 | for key, formatter in self.formatters.items(): |
|
80 | for key, formatter in self.formatters.items(): | |
81 | if key in new: |
|
81 | if key in new: | |
82 | formatter.enabled = True |
|
82 | formatter.enabled = True | |
83 | else: |
|
83 | else: | |
84 | formatter.enabled = False |
|
84 | formatter.enabled = False | |
85 |
|
85 | |||
86 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
86 | # A dict of formatter whose keys are format types (MIME types) and whose | |
87 | # values are subclasses of BaseFormatter. |
|
87 | # values are subclasses of BaseFormatter. | |
88 | formatters = Dict() |
|
88 | formatters = Dict() | |
89 | def _formatters_default(self): |
|
89 | def _formatters_default(self): | |
90 | """Activate the default formatters.""" |
|
90 | """Activate the default formatters.""" | |
91 | formatter_classes = [ |
|
91 | formatter_classes = [ | |
92 | PlainTextFormatter, |
|
92 | PlainTextFormatter, | |
93 | HTMLFormatter, |
|
93 | HTMLFormatter, | |
94 | SVGFormatter, |
|
94 | SVGFormatter, | |
95 | PNGFormatter, |
|
95 | PNGFormatter, | |
96 | JPEGFormatter, |
|
96 | JPEGFormatter, | |
97 | LatexFormatter, |
|
97 | LatexFormatter, | |
98 | JSONFormatter, |
|
98 | JSONFormatter, | |
99 | JavascriptFormatter |
|
99 | JavascriptFormatter | |
100 | ] |
|
100 | ] | |
101 | d = {} |
|
101 | d = {} | |
102 | for cls in formatter_classes: |
|
102 | for cls in formatter_classes: | |
103 | f = cls(parent=self) |
|
103 | f = cls(parent=self) | |
104 | d[f.format_type] = f |
|
104 | d[f.format_type] = f | |
105 | return d |
|
105 | return d | |
106 |
|
106 | |||
107 | def format(self, obj, include=None, exclude=None): |
|
107 | def format(self, obj, include=None, exclude=None): | |
108 | """Return a format data dict for an object. |
|
108 | """Return a format data dict for an object. | |
109 |
|
109 | |||
110 | By default all format types will be computed. |
|
110 | By default all format types will be computed. | |
111 |
|
111 | |||
112 | The following MIME types are currently implemented: |
|
112 | The following MIME types are currently implemented: | |
113 |
|
113 | |||
114 | * text/plain |
|
114 | * text/plain | |
115 | * text/html |
|
115 | * text/html | |
116 | * text/latex |
|
116 | * text/latex | |
117 | * application/json |
|
117 | * application/json | |
118 | * application/javascript |
|
118 | * application/javascript | |
119 | * image/png |
|
119 | * image/png | |
120 | * image/jpeg |
|
120 | * image/jpeg | |
121 | * image/svg+xml |
|
121 | * image/svg+xml | |
122 |
|
122 | |||
123 | Parameters |
|
123 | Parameters | |
124 | ---------- |
|
124 | ---------- | |
125 | obj : object |
|
125 | obj : object | |
126 | The Python object whose format data will be computed. |
|
126 | The Python object whose format data will be computed. | |
127 | include : list or tuple, optional |
|
127 | include : list or tuple, optional | |
128 | A list of format type strings (MIME types) to include in the |
|
128 | A list of format type strings (MIME types) to include in the | |
129 | format data dict. If this is set *only* the format types included |
|
129 | format data dict. If this is set *only* the format types included | |
130 | in this list will be computed. |
|
130 | in this list will be computed. | |
131 | exclude : list or tuple, optional |
|
131 | exclude : list or tuple, optional | |
132 | A list of format type string (MIME types) to exclude in the format |
|
132 | A list of format type string (MIME types) to exclude in the format | |
133 | data dict. If this is set all format types will be computed, |
|
133 | data dict. If this is set all format types will be computed, | |
134 | except for those included in this argument. |
|
134 | except for those included in this argument. | |
135 |
|
135 | |||
136 | Returns |
|
136 | Returns | |
137 | ------- |
|
137 | ------- | |
138 | (format_dict, metadata_dict) : tuple of two dicts |
|
138 | (format_dict, metadata_dict) : tuple of two dicts | |
139 |
|
139 | |||
140 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
140 | format_dict is a dictionary of key/value pairs, one of each format that was | |
141 | generated for the object. The keys are the format types, which |
|
141 | generated for the object. The keys are the format types, which | |
142 | will usually be MIME type strings and the values and JSON'able |
|
142 | will usually be MIME type strings and the values and JSON'able | |
143 | data structure containing the raw data for the representation in |
|
143 | data structure containing the raw data for the representation in | |
144 | that format. |
|
144 | that format. | |
145 |
|
145 | |||
146 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
146 | metadata_dict is a dictionary of metadata about each mime-type output. | |
147 | Its keys will be a strict subset of the keys in format_dict. |
|
147 | Its keys will be a strict subset of the keys in format_dict. | |
148 | """ |
|
148 | """ | |
149 | format_dict = {} |
|
149 | format_dict = {} | |
150 | md_dict = {} |
|
150 | md_dict = {} | |
151 |
|
151 | |||
152 | # If _ipython_display_ is defined, use that to display this object. If |
|
152 | for format_type, formatter in self.formatters.items(): | |
153 | # it returns NotImplemented, use the _repr_ logic (default). |
|
153 | if include and format_type not in include: | |
154 | if not hasattr(obj, '_ipython_display_') or obj._ipython_display_(**kwargs) == NotImplemented: |
|
154 | continue | |
155 | for format_type, formatter in self.formatters.items(): |
|
155 | if exclude and format_type in exclude: | |
156 | if include and format_type not in include: |
|
156 | continue | |
157 |
|
|
157 | ||
158 | if exclude and format_type in exclude: |
|
158 | md = None | |
159 | continue |
|
159 | try: | |
160 |
|
160 | data = formatter(obj) | ||
161 | md = None |
|
161 | except: | |
162 | try: |
|
162 | # FIXME: log the exception | |
163 | data = formatter(obj) |
|
163 | raise | |
164 |
|
|
164 | ||
165 | # FIXME: log the exception |
|
165 | # formatters can return raw data or (data, metadata) | |
166 | raise |
|
166 | if isinstance(data, tuple) and len(data) == 2: | |
167 |
|
167 | data, md = data | ||
168 | # formatters can return raw data or (data, metadata) |
|
168 | ||
169 | if isinstance(data, tuple) and len(data) == 2: |
|
169 | if data is not None: | |
170 |
|
|
170 | format_dict[format_type] = data | |
171 |
|
171 | if md is not None: | ||
172 | if data is not None: |
|
172 | md_dict[format_type] = md | |
173 | format_dict[format_type] = data |
|
|||
174 | if md is not None: |
|
|||
175 | md_dict[format_type] = md |
|
|||
176 |
|
173 | |||
177 | return format_dict, md_dict |
|
174 | return format_dict, md_dict | |
178 |
|
175 | |||
179 | @property |
|
176 | @property | |
180 | def format_types(self): |
|
177 | def format_types(self): | |
181 | """Return the format types (MIME types) of the active formatters.""" |
|
178 | """Return the format types (MIME types) of the active formatters.""" | |
182 | return list(self.formatters.keys()) |
|
179 | return list(self.formatters.keys()) | |
183 |
|
180 | |||
184 |
|
181 | |||
185 | #----------------------------------------------------------------------------- |
|
182 | #----------------------------------------------------------------------------- | |
186 | # Formatters for specific format types (text, html, svg, etc.) |
|
183 | # Formatters for specific format types (text, html, svg, etc.) | |
187 | #----------------------------------------------------------------------------- |
|
184 | #----------------------------------------------------------------------------- | |
188 |
|
185 | |||
189 | @decorator |
|
186 | @decorator | |
190 | def warn_format_error(method, self, *args, **kwargs): |
|
187 | def warn_format_error(method, self, *args, **kwargs): | |
191 | """decorator for warning on failed format call""" |
|
188 | """decorator for warning on failed format call""" | |
192 | try: |
|
189 | try: | |
193 | r = method(self, *args, **kwargs) |
|
190 | r = method(self, *args, **kwargs) | |
194 | except Exception as e: |
|
191 | except Exception as e: | |
195 | warn("Exception in %s formatter: %s" % (self.format_type, e)) |
|
192 | warn("Exception in %s formatter: %s" % (self.format_type, e)) | |
196 | return None |
|
193 | return None | |
197 | if r is None or isinstance(r, self._return_type) or \ |
|
194 | if r is None or isinstance(r, self._return_type) or \ | |
198 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): |
|
195 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): | |
199 | return r |
|
196 | return r | |
200 | else: |
|
197 | else: | |
201 | warn("%s formatter returned invalid type %s (expected %s) for object: %s" % ( |
|
198 | warn("%s formatter returned invalid type %s (expected %s) for object: %s" % ( | |
202 | self.format_type, type(r), self._return_type, pretty._safe_repr(args[0]) |
|
199 | self.format_type, type(r), self._return_type, pretty._safe_repr(args[0]) | |
203 | )) |
|
200 | )) | |
204 |
|
201 | |||
205 |
|
202 | |||
206 |
|
203 | |||
207 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
204 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): | |
208 | """ Abstract base class for Formatters. |
|
205 | """ Abstract base class for Formatters. | |
209 |
|
206 | |||
210 | A formatter is a callable class that is responsible for computing the |
|
207 | A formatter is a callable class that is responsible for computing the | |
211 | raw format data for a particular format type (MIME type). For example, |
|
208 | raw format data for a particular format type (MIME type). For example, | |
212 | an HTML formatter would have a format type of `text/html` and would return |
|
209 | an HTML formatter would have a format type of `text/html` and would return | |
213 | the HTML representation of the object when called. |
|
210 | the HTML representation of the object when called. | |
214 | """ |
|
211 | """ | |
215 |
|
212 | |||
216 | # The format type of the data returned, usually a MIME type. |
|
213 | # The format type of the data returned, usually a MIME type. | |
217 | format_type = 'text/plain' |
|
214 | format_type = 'text/plain' | |
218 |
|
215 | |||
219 | # Is the formatter enabled... |
|
216 | # Is the formatter enabled... | |
220 | enabled = True |
|
217 | enabled = True | |
221 |
|
218 | |||
222 | @abc.abstractmethod |
|
219 | @abc.abstractmethod | |
223 | @warn_format_error |
|
220 | @warn_format_error | |
224 | def __call__(self, obj): |
|
221 | def __call__(self, obj): | |
225 | """Return a JSON'able representation of the object. |
|
222 | """Return a JSON'able representation of the object. | |
226 |
|
223 | |||
227 | If the object cannot be formatted by this formatter, |
|
224 | If the object cannot be formatted by this formatter, | |
228 | warn and return None. |
|
225 | warn and return None. | |
229 | """ |
|
226 | """ | |
230 | return repr(obj) |
|
227 | return repr(obj) | |
231 |
|
228 | |||
232 |
|
229 | |||
233 | def _mod_name_key(typ): |
|
230 | def _mod_name_key(typ): | |
234 | """Return a (__module__, __name__) tuple for a type. |
|
231 | """Return a (__module__, __name__) tuple for a type. | |
235 |
|
232 | |||
236 | Used as key in Formatter.deferred_printers. |
|
233 | Used as key in Formatter.deferred_printers. | |
237 | """ |
|
234 | """ | |
238 | module = getattr(typ, '__module__', None) |
|
235 | module = getattr(typ, '__module__', None) | |
239 | name = getattr(typ, '__name__', None) |
|
236 | name = getattr(typ, '__name__', None) | |
240 | return (module, name) |
|
237 | return (module, name) | |
241 |
|
238 | |||
242 |
|
239 | |||
243 | def _get_type(obj): |
|
240 | def _get_type(obj): | |
244 | """Return the type of an instance (old and new-style)""" |
|
241 | """Return the type of an instance (old and new-style)""" | |
245 | return getattr(obj, '__class__', None) or type(obj) |
|
242 | return getattr(obj, '__class__', None) or type(obj) | |
246 |
|
243 | |||
247 | _raise_key_error = object() |
|
244 | _raise_key_error = object() | |
248 |
|
245 | |||
249 |
|
246 | |||
250 | class BaseFormatter(Configurable): |
|
247 | class BaseFormatter(Configurable): | |
251 | """A base formatter class that is configurable. |
|
248 | """A base formatter class that is configurable. | |
252 |
|
249 | |||
253 | This formatter should usually be used as the base class of all formatters. |
|
250 | This formatter should usually be used as the base class of all formatters. | |
254 | It is a traited :class:`Configurable` class and includes an extensible |
|
251 | It is a traited :class:`Configurable` class and includes an extensible | |
255 | API for users to determine how their objects are formatted. The following |
|
252 | API for users to determine how their objects are formatted. The following | |
256 | logic is used to find a function to format an given object. |
|
253 | logic is used to find a function to format an given object. | |
257 |
|
254 | |||
258 | 1. The object is introspected to see if it has a method with the name |
|
255 | 1. The object is introspected to see if it has a method with the name | |
259 | :attr:`print_method`. If is does, that object is passed to that method |
|
256 | :attr:`print_method`. If is does, that object is passed to that method | |
260 | for formatting. |
|
257 | for formatting. | |
261 | 2. If no print method is found, three internal dictionaries are consulted |
|
258 | 2. If no print method is found, three internal dictionaries are consulted | |
262 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
259 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
263 | and :attr:`deferred_printers`. |
|
260 | and :attr:`deferred_printers`. | |
264 |
|
261 | |||
265 | Users should use these dictionaries to register functions that will be |
|
262 | Users should use these dictionaries to register functions that will be | |
266 | used to compute the format data for their objects (if those objects don't |
|
263 | used to compute the format data for their objects (if those objects don't | |
267 | have the special print methods). The easiest way of using these |
|
264 | have the special print methods). The easiest way of using these | |
268 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
265 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` | |
269 | methods. |
|
266 | methods. | |
270 |
|
267 | |||
271 | If no function/callable is found to compute the format data, ``None`` is |
|
268 | If no function/callable is found to compute the format data, ``None`` is | |
272 | returned and this format type is not used. |
|
269 | returned and this format type is not used. | |
273 | """ |
|
270 | """ | |
274 |
|
271 | |||
275 | format_type = Unicode('text/plain') |
|
272 | format_type = Unicode('text/plain') | |
276 | _return_type = string_types |
|
273 | _return_type = string_types | |
277 |
|
274 | |||
278 | enabled = Bool(True, config=True) |
|
275 | enabled = Bool(True, config=True) | |
279 |
|
276 | |||
280 | print_method = ObjectName('__repr__') |
|
277 | print_method = ObjectName('__repr__') | |
281 |
|
278 | |||
282 | # The singleton printers. |
|
279 | # The singleton printers. | |
283 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
280 | # Maps the IDs of the builtin singleton objects to the format functions. | |
284 | singleton_printers = Dict(config=True) |
|
281 | singleton_printers = Dict(config=True) | |
285 |
|
282 | |||
286 | # The type-specific printers. |
|
283 | # The type-specific printers. | |
287 | # Map type objects to the format functions. |
|
284 | # Map type objects to the format functions. | |
288 | type_printers = Dict(config=True) |
|
285 | type_printers = Dict(config=True) | |
289 |
|
286 | |||
290 | # The deferred-import type-specific printers. |
|
287 | # The deferred-import type-specific printers. | |
291 | # Map (modulename, classname) pairs to the format functions. |
|
288 | # Map (modulename, classname) pairs to the format functions. | |
292 | deferred_printers = Dict(config=True) |
|
289 | deferred_printers = Dict(config=True) | |
293 |
|
290 | |||
294 | @warn_format_error |
|
291 | @warn_format_error | |
295 | def __call__(self, obj): |
|
292 | def __call__(self, obj): | |
296 | """Compute the format for an object.""" |
|
293 | """Compute the format for an object.""" | |
297 | if self.enabled: |
|
294 | if self.enabled: | |
298 | # lookup registered printer |
|
295 | # lookup registered printer | |
299 | try: |
|
296 | try: | |
300 | printer = self.lookup(obj) |
|
297 | printer = self.lookup(obj) | |
301 | except KeyError: |
|
298 | except KeyError: | |
302 | pass |
|
299 | pass | |
303 | else: |
|
300 | else: | |
304 | return printer(obj) |
|
301 | return printer(obj) | |
305 | # Finally look for special method names |
|
302 | # Finally look for special method names | |
306 | method = pretty._safe_getattr(obj, self.print_method, None) |
|
303 | method = pretty._safe_getattr(obj, self.print_method, None) | |
307 | if method is not None: |
|
304 | if method is not None: | |
308 | return method() |
|
305 | return method() | |
309 | return None |
|
306 | return None | |
310 | else: |
|
307 | else: | |
311 | return None |
|
308 | return None | |
312 |
|
309 | |||
313 | def __contains__(self, typ): |
|
310 | def __contains__(self, typ): | |
314 | """map in to lookup_by_type""" |
|
311 | """map in to lookup_by_type""" | |
315 | try: |
|
312 | try: | |
316 | self.lookup_by_type(typ) |
|
313 | self.lookup_by_type(typ) | |
317 | except KeyError: |
|
314 | except KeyError: | |
318 | return False |
|
315 | return False | |
319 | else: |
|
316 | else: | |
320 | return True |
|
317 | return True | |
321 |
|
318 | |||
322 | def lookup(self, obj): |
|
319 | def lookup(self, obj): | |
323 | """Look up the formatter for a given instance. |
|
320 | """Look up the formatter for a given instance. | |
324 |
|
321 | |||
325 | Parameters |
|
322 | Parameters | |
326 | ---------- |
|
323 | ---------- | |
327 | obj : object instance |
|
324 | obj : object instance | |
328 |
|
325 | |||
329 | Returns |
|
326 | Returns | |
330 | ------- |
|
327 | ------- | |
331 | f : callable |
|
328 | f : callable | |
332 | The registered formatting callable for the type. |
|
329 | The registered formatting callable for the type. | |
333 |
|
330 | |||
334 | Raises |
|
331 | Raises | |
335 | ------ |
|
332 | ------ | |
336 | KeyError if the type has not been registered. |
|
333 | KeyError if the type has not been registered. | |
337 | """ |
|
334 | """ | |
338 | # look for singleton first |
|
335 | # look for singleton first | |
339 | obj_id = id(obj) |
|
336 | obj_id = id(obj) | |
340 | if obj_id in self.singleton_printers: |
|
337 | if obj_id in self.singleton_printers: | |
341 | return self.singleton_printers[obj_id] |
|
338 | return self.singleton_printers[obj_id] | |
342 | # then lookup by type |
|
339 | # then lookup by type | |
343 | return self.lookup_by_type(_get_type(obj)) |
|
340 | return self.lookup_by_type(_get_type(obj)) | |
344 |
|
341 | |||
345 | def lookup_by_type(self, typ): |
|
342 | def lookup_by_type(self, typ): | |
346 | """Look up the registered formatter for a type. |
|
343 | """Look up the registered formatter for a type. | |
347 |
|
344 | |||
348 | Parameters |
|
345 | Parameters | |
349 | ---------- |
|
346 | ---------- | |
350 | typ : type or '__module__.__name__' string for a type |
|
347 | typ : type or '__module__.__name__' string for a type | |
351 |
|
348 | |||
352 | Returns |
|
349 | Returns | |
353 | ------- |
|
350 | ------- | |
354 | f : callable |
|
351 | f : callable | |
355 | The registered formatting callable for the type. |
|
352 | The registered formatting callable for the type. | |
356 |
|
353 | |||
357 | Raises |
|
354 | Raises | |
358 | ------ |
|
355 | ------ | |
359 | KeyError if the type has not been registered. |
|
356 | KeyError if the type has not been registered. | |
360 | """ |
|
357 | """ | |
361 | if isinstance(typ, string_types): |
|
358 | if isinstance(typ, string_types): | |
362 | typ_key = tuple(typ.rsplit('.',1)) |
|
359 | typ_key = tuple(typ.rsplit('.',1)) | |
363 | if typ_key not in self.deferred_printers: |
|
360 | if typ_key not in self.deferred_printers: | |
364 | # We may have it cached in the type map. We will have to |
|
361 | # We may have it cached in the type map. We will have to | |
365 | # iterate over all of the types to check. |
|
362 | # iterate over all of the types to check. | |
366 | for cls in self.type_printers: |
|
363 | for cls in self.type_printers: | |
367 | if _mod_name_key(cls) == typ_key: |
|
364 | if _mod_name_key(cls) == typ_key: | |
368 | return self.type_printers[cls] |
|
365 | return self.type_printers[cls] | |
369 | else: |
|
366 | else: | |
370 | return self.deferred_printers[typ_key] |
|
367 | return self.deferred_printers[typ_key] | |
371 | else: |
|
368 | else: | |
372 | for cls in pretty._get_mro(typ): |
|
369 | for cls in pretty._get_mro(typ): | |
373 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
370 | if cls in self.type_printers or self._in_deferred_types(cls): | |
374 | return self.type_printers[cls] |
|
371 | return self.type_printers[cls] | |
375 |
|
372 | |||
376 | # If we have reached here, the lookup failed. |
|
373 | # If we have reached here, the lookup failed. | |
377 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
374 | raise KeyError("No registered printer for {0!r}".format(typ)) | |
378 |
|
375 | |||
379 | def for_type(self, typ, func=None): |
|
376 | def for_type(self, typ, func=None): | |
380 | """Add a format function for a given type. |
|
377 | """Add a format function for a given type. | |
381 |
|
378 | |||
382 | Parameters |
|
379 | Parameters | |
383 | ----------- |
|
380 | ----------- | |
384 | typ : type or '__module__.__name__' string for a type |
|
381 | typ : type or '__module__.__name__' string for a type | |
385 | The class of the object that will be formatted using `func`. |
|
382 | The class of the object that will be formatted using `func`. | |
386 | func : callable |
|
383 | func : callable | |
387 | A callable for computing the format data. |
|
384 | A callable for computing the format data. | |
388 | `func` will be called with the object to be formatted, |
|
385 | `func` will be called with the object to be formatted, | |
389 | and will return the raw data in this formatter's format. |
|
386 | and will return the raw data in this formatter's format. | |
390 | Subclasses may use a different call signature for the |
|
387 | Subclasses may use a different call signature for the | |
391 | `func` argument. |
|
388 | `func` argument. | |
392 |
|
389 | |||
393 | If `func` is None or not specified, there will be no change, |
|
390 | If `func` is None or not specified, there will be no change, | |
394 | only returning the current value. |
|
391 | only returning the current value. | |
395 |
|
392 | |||
396 | Returns |
|
393 | Returns | |
397 | ------- |
|
394 | ------- | |
398 | oldfunc : callable |
|
395 | oldfunc : callable | |
399 | The currently registered callable. |
|
396 | The currently registered callable. | |
400 | If you are registering a new formatter, |
|
397 | If you are registering a new formatter, | |
401 | this will be the previous value (to enable restoring later). |
|
398 | this will be the previous value (to enable restoring later). | |
402 | """ |
|
399 | """ | |
403 | # if string given, interpret as 'pkg.module.class_name' |
|
400 | # if string given, interpret as 'pkg.module.class_name' | |
404 | if isinstance(typ, string_types): |
|
401 | if isinstance(typ, string_types): | |
405 | type_module, type_name = typ.rsplit('.', 1) |
|
402 | type_module, type_name = typ.rsplit('.', 1) | |
406 | return self.for_type_by_name(type_module, type_name, func) |
|
403 | return self.for_type_by_name(type_module, type_name, func) | |
407 |
|
404 | |||
408 | try: |
|
405 | try: | |
409 | oldfunc = self.lookup_by_type(typ) |
|
406 | oldfunc = self.lookup_by_type(typ) | |
410 | except KeyError: |
|
407 | except KeyError: | |
411 | oldfunc = None |
|
408 | oldfunc = None | |
412 |
|
409 | |||
413 | if func is not None: |
|
410 | if func is not None: | |
414 | self.type_printers[typ] = func |
|
411 | self.type_printers[typ] = func | |
415 |
|
412 | |||
416 | return oldfunc |
|
413 | return oldfunc | |
417 |
|
414 | |||
418 | def for_type_by_name(self, type_module, type_name, func=None): |
|
415 | def for_type_by_name(self, type_module, type_name, func=None): | |
419 | """Add a format function for a type specified by the full dotted |
|
416 | """Add a format function for a type specified by the full dotted | |
420 | module and name of the type, rather than the type of the object. |
|
417 | module and name of the type, rather than the type of the object. | |
421 |
|
418 | |||
422 | Parameters |
|
419 | Parameters | |
423 | ---------- |
|
420 | ---------- | |
424 | type_module : str |
|
421 | type_module : str | |
425 | The full dotted name of the module the type is defined in, like |
|
422 | The full dotted name of the module the type is defined in, like | |
426 | ``numpy``. |
|
423 | ``numpy``. | |
427 | type_name : str |
|
424 | type_name : str | |
428 | The name of the type (the class name), like ``dtype`` |
|
425 | The name of the type (the class name), like ``dtype`` | |
429 | func : callable |
|
426 | func : callable | |
430 | A callable for computing the format data. |
|
427 | A callable for computing the format data. | |
431 | `func` will be called with the object to be formatted, |
|
428 | `func` will be called with the object to be formatted, | |
432 | and will return the raw data in this formatter's format. |
|
429 | and will return the raw data in this formatter's format. | |
433 | Subclasses may use a different call signature for the |
|
430 | Subclasses may use a different call signature for the | |
434 | `func` argument. |
|
431 | `func` argument. | |
435 |
|
432 | |||
436 | If `func` is None or unspecified, there will be no change, |
|
433 | If `func` is None or unspecified, there will be no change, | |
437 | only returning the current value. |
|
434 | only returning the current value. | |
438 |
|
435 | |||
439 | Returns |
|
436 | Returns | |
440 | ------- |
|
437 | ------- | |
441 | oldfunc : callable |
|
438 | oldfunc : callable | |
442 | The currently registered callable. |
|
439 | The currently registered callable. | |
443 | If you are registering a new formatter, |
|
440 | If you are registering a new formatter, | |
444 | this will be the previous value (to enable restoring later). |
|
441 | this will be the previous value (to enable restoring later). | |
445 | """ |
|
442 | """ | |
446 | key = (type_module, type_name) |
|
443 | key = (type_module, type_name) | |
447 |
|
444 | |||
448 | try: |
|
445 | try: | |
449 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
446 | oldfunc = self.lookup_by_type("%s.%s" % key) | |
450 | except KeyError: |
|
447 | except KeyError: | |
451 | oldfunc = None |
|
448 | oldfunc = None | |
452 |
|
449 | |||
453 | if func is not None: |
|
450 | if func is not None: | |
454 | self.deferred_printers[key] = func |
|
451 | self.deferred_printers[key] = func | |
455 | return oldfunc |
|
452 | return oldfunc | |
456 |
|
453 | |||
457 | def pop(self, typ, default=_raise_key_error): |
|
454 | def pop(self, typ, default=_raise_key_error): | |
458 | """Pop a formatter for the given type. |
|
455 | """Pop a formatter for the given type. | |
459 |
|
456 | |||
460 | Parameters |
|
457 | Parameters | |
461 | ---------- |
|
458 | ---------- | |
462 | typ : type or '__module__.__name__' string for a type |
|
459 | typ : type or '__module__.__name__' string for a type | |
463 | default : object |
|
460 | default : object | |
464 | value to be returned if no formatter is registered for typ. |
|
461 | value to be returned if no formatter is registered for typ. | |
465 |
|
462 | |||
466 | Returns |
|
463 | Returns | |
467 | ------- |
|
464 | ------- | |
468 | obj : object |
|
465 | obj : object | |
469 | The last registered object for the type. |
|
466 | The last registered object for the type. | |
470 |
|
467 | |||
471 | Raises |
|
468 | Raises | |
472 | ------ |
|
469 | ------ | |
473 | KeyError if the type is not registered and default is not specified. |
|
470 | KeyError if the type is not registered and default is not specified. | |
474 | """ |
|
471 | """ | |
475 |
|
472 | |||
476 | if isinstance(typ, string_types): |
|
473 | if isinstance(typ, string_types): | |
477 | typ_key = tuple(typ.rsplit('.',1)) |
|
474 | typ_key = tuple(typ.rsplit('.',1)) | |
478 | if typ_key not in self.deferred_printers: |
|
475 | if typ_key not in self.deferred_printers: | |
479 | # We may have it cached in the type map. We will have to |
|
476 | # We may have it cached in the type map. We will have to | |
480 | # iterate over all of the types to check. |
|
477 | # iterate over all of the types to check. | |
481 | for cls in self.type_printers: |
|
478 | for cls in self.type_printers: | |
482 | if _mod_name_key(cls) == typ_key: |
|
479 | if _mod_name_key(cls) == typ_key: | |
483 | old = self.type_printers.pop(cls) |
|
480 | old = self.type_printers.pop(cls) | |
484 | break |
|
481 | break | |
485 | else: |
|
482 | else: | |
486 | old = default |
|
483 | old = default | |
487 | else: |
|
484 | else: | |
488 | old = self.deferred_printers.pop(typ_key) |
|
485 | old = self.deferred_printers.pop(typ_key) | |
489 | else: |
|
486 | else: | |
490 | if typ in self.type_printers: |
|
487 | if typ in self.type_printers: | |
491 | old = self.type_printers.pop(typ) |
|
488 | old = self.type_printers.pop(typ) | |
492 | else: |
|
489 | else: | |
493 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
490 | old = self.deferred_printers.pop(_mod_name_key(typ), default) | |
494 | if old is _raise_key_error: |
|
491 | if old is _raise_key_error: | |
495 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
492 | raise KeyError("No registered value for {0!r}".format(typ)) | |
496 | return old |
|
493 | return old | |
497 |
|
494 | |||
498 | def _in_deferred_types(self, cls): |
|
495 | def _in_deferred_types(self, cls): | |
499 | """ |
|
496 | """ | |
500 | Check if the given class is specified in the deferred type registry. |
|
497 | Check if the given class is specified in the deferred type registry. | |
501 |
|
498 | |||
502 | Successful matches will be moved to the regular type registry for future use. |
|
499 | Successful matches will be moved to the regular type registry for future use. | |
503 | """ |
|
500 | """ | |
504 | mod = getattr(cls, '__module__', None) |
|
501 | mod = getattr(cls, '__module__', None) | |
505 | name = getattr(cls, '__name__', None) |
|
502 | name = getattr(cls, '__name__', None) | |
506 | key = (mod, name) |
|
503 | key = (mod, name) | |
507 | if key in self.deferred_printers: |
|
504 | if key in self.deferred_printers: | |
508 | # Move the printer over to the regular registry. |
|
505 | # Move the printer over to the regular registry. | |
509 | printer = self.deferred_printers.pop(key) |
|
506 | printer = self.deferred_printers.pop(key) | |
510 | self.type_printers[cls] = printer |
|
507 | self.type_printers[cls] = printer | |
511 | return True |
|
508 | return True | |
512 | return False |
|
509 | return False | |
513 |
|
510 | |||
514 |
|
511 | |||
515 | class PlainTextFormatter(BaseFormatter): |
|
512 | class PlainTextFormatter(BaseFormatter): | |
516 | """The default pretty-printer. |
|
513 | """The default pretty-printer. | |
517 |
|
514 | |||
518 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
515 | This uses :mod:`IPython.lib.pretty` to compute the format data of | |
519 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
516 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
520 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
517 | See the documentation of :mod:`IPython.lib.pretty` for details on | |
521 | how to write pretty printers. Here is a simple example:: |
|
518 | how to write pretty printers. Here is a simple example:: | |
522 |
|
519 | |||
523 | def dtype_pprinter(obj, p, cycle): |
|
520 | def dtype_pprinter(obj, p, cycle): | |
524 | if cycle: |
|
521 | if cycle: | |
525 | return p.text('dtype(...)') |
|
522 | return p.text('dtype(...)') | |
526 | if hasattr(obj, 'fields'): |
|
523 | if hasattr(obj, 'fields'): | |
527 | if obj.fields is None: |
|
524 | if obj.fields is None: | |
528 | p.text(repr(obj)) |
|
525 | p.text(repr(obj)) | |
529 | else: |
|
526 | else: | |
530 | p.begin_group(7, 'dtype([') |
|
527 | p.begin_group(7, 'dtype([') | |
531 | for i, field in enumerate(obj.descr): |
|
528 | for i, field in enumerate(obj.descr): | |
532 | if i > 0: |
|
529 | if i > 0: | |
533 | p.text(',') |
|
530 | p.text(',') | |
534 | p.breakable() |
|
531 | p.breakable() | |
535 | p.pretty(field) |
|
532 | p.pretty(field) | |
536 | p.end_group(7, '])') |
|
533 | p.end_group(7, '])') | |
537 | """ |
|
534 | """ | |
538 |
|
535 | |||
539 | # The format type of data returned. |
|
536 | # The format type of data returned. | |
540 | format_type = Unicode('text/plain') |
|
537 | format_type = Unicode('text/plain') | |
541 |
|
538 | |||
542 | # This subclass ignores this attribute as it always need to return |
|
539 | # This subclass ignores this attribute as it always need to return | |
543 | # something. |
|
540 | # something. | |
544 | enabled = Bool(True, config=False) |
|
541 | enabled = Bool(True, config=False) | |
545 |
|
542 | |||
546 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
543 | # Look for a _repr_pretty_ methods to use for pretty printing. | |
547 | print_method = ObjectName('_repr_pretty_') |
|
544 | print_method = ObjectName('_repr_pretty_') | |
548 |
|
545 | |||
549 | # Whether to pretty-print or not. |
|
546 | # Whether to pretty-print or not. | |
550 | pprint = Bool(True, config=True) |
|
547 | pprint = Bool(True, config=True) | |
551 |
|
548 | |||
552 | # Whether to be verbose or not. |
|
549 | # Whether to be verbose or not. | |
553 | verbose = Bool(False, config=True) |
|
550 | verbose = Bool(False, config=True) | |
554 |
|
551 | |||
555 | # The maximum width. |
|
552 | # The maximum width. | |
556 | max_width = Integer(79, config=True) |
|
553 | max_width = Integer(79, config=True) | |
557 |
|
554 | |||
558 | # The newline character. |
|
555 | # The newline character. | |
559 | newline = Unicode('\n', config=True) |
|
556 | newline = Unicode('\n', config=True) | |
560 |
|
557 | |||
561 | # format-string for pprinting floats |
|
558 | # format-string for pprinting floats | |
562 | float_format = Unicode('%r') |
|
559 | float_format = Unicode('%r') | |
563 | # setter for float precision, either int or direct format-string |
|
560 | # setter for float precision, either int or direct format-string | |
564 | float_precision = CUnicode('', config=True) |
|
561 | float_precision = CUnicode('', config=True) | |
565 |
|
562 | |||
566 | def _float_precision_changed(self, name, old, new): |
|
563 | def _float_precision_changed(self, name, old, new): | |
567 | """float_precision changed, set float_format accordingly. |
|
564 | """float_precision changed, set float_format accordingly. | |
568 |
|
565 | |||
569 | float_precision can be set by int or str. |
|
566 | float_precision can be set by int or str. | |
570 | This will set float_format, after interpreting input. |
|
567 | This will set float_format, after interpreting input. | |
571 | If numpy has been imported, numpy print precision will also be set. |
|
568 | If numpy has been imported, numpy print precision will also be set. | |
572 |
|
569 | |||
573 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
570 | integer `n` sets format to '%.nf', otherwise, format set directly. | |
574 |
|
571 | |||
575 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
572 | An empty string returns to defaults (repr for float, 8 for numpy). | |
576 |
|
573 | |||
577 | This parameter can be set via the '%precision' magic. |
|
574 | This parameter can be set via the '%precision' magic. | |
578 | """ |
|
575 | """ | |
579 |
|
576 | |||
580 | if '%' in new: |
|
577 | if '%' in new: | |
581 | # got explicit format string |
|
578 | # got explicit format string | |
582 | fmt = new |
|
579 | fmt = new | |
583 | try: |
|
580 | try: | |
584 | fmt%3.14159 |
|
581 | fmt%3.14159 | |
585 | except Exception: |
|
582 | except Exception: | |
586 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
583 | raise ValueError("Precision must be int or format string, not %r"%new) | |
587 | elif new: |
|
584 | elif new: | |
588 | # otherwise, should be an int |
|
585 | # otherwise, should be an int | |
589 | try: |
|
586 | try: | |
590 | i = int(new) |
|
587 | i = int(new) | |
591 | assert i >= 0 |
|
588 | assert i >= 0 | |
592 | except ValueError: |
|
589 | except ValueError: | |
593 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
590 | raise ValueError("Precision must be int or format string, not %r"%new) | |
594 | except AssertionError: |
|
591 | except AssertionError: | |
595 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
592 | raise ValueError("int precision must be non-negative, not %r"%i) | |
596 |
|
593 | |||
597 | fmt = '%%.%if'%i |
|
594 | fmt = '%%.%if'%i | |
598 | if 'numpy' in sys.modules: |
|
595 | if 'numpy' in sys.modules: | |
599 | # set numpy precision if it has been imported |
|
596 | # set numpy precision if it has been imported | |
600 | import numpy |
|
597 | import numpy | |
601 | numpy.set_printoptions(precision=i) |
|
598 | numpy.set_printoptions(precision=i) | |
602 | else: |
|
599 | else: | |
603 | # default back to repr |
|
600 | # default back to repr | |
604 | fmt = '%r' |
|
601 | fmt = '%r' | |
605 | if 'numpy' in sys.modules: |
|
602 | if 'numpy' in sys.modules: | |
606 | import numpy |
|
603 | import numpy | |
607 | # numpy default is 8 |
|
604 | # numpy default is 8 | |
608 | numpy.set_printoptions(precision=8) |
|
605 | numpy.set_printoptions(precision=8) | |
609 | self.float_format = fmt |
|
606 | self.float_format = fmt | |
610 |
|
607 | |||
611 | # Use the default pretty printers from IPython.lib.pretty. |
|
608 | # Use the default pretty printers from IPython.lib.pretty. | |
612 | def _singleton_printers_default(self): |
|
609 | def _singleton_printers_default(self): | |
613 | return pretty._singleton_pprinters.copy() |
|
610 | return pretty._singleton_pprinters.copy() | |
614 |
|
611 | |||
615 | def _type_printers_default(self): |
|
612 | def _type_printers_default(self): | |
616 | d = pretty._type_pprinters.copy() |
|
613 | d = pretty._type_pprinters.copy() | |
617 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
614 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) | |
618 | return d |
|
615 | return d | |
619 |
|
616 | |||
620 | def _deferred_printers_default(self): |
|
617 | def _deferred_printers_default(self): | |
621 | return pretty._deferred_type_pprinters.copy() |
|
618 | return pretty._deferred_type_pprinters.copy() | |
622 |
|
619 | |||
623 | #### FormatterABC interface #### |
|
620 | #### FormatterABC interface #### | |
624 |
|
621 | |||
625 | @warn_format_error |
|
622 | @warn_format_error | |
626 | def __call__(self, obj): |
|
623 | def __call__(self, obj): | |
627 | """Compute the pretty representation of the object.""" |
|
624 | """Compute the pretty representation of the object.""" | |
628 | if not self.pprint: |
|
625 | if not self.pprint: | |
629 | return pretty._safe_repr(obj) |
|
626 | return pretty._safe_repr(obj) | |
630 | else: |
|
627 | else: | |
631 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
628 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
632 | stream = StringIO() |
|
629 | stream = StringIO() | |
633 | # self.newline.encode() is a quick fix for issue gh-597. We need to |
|
630 | # self.newline.encode() is a quick fix for issue gh-597. We need to | |
634 | # ensure that stream does not get a mix of unicode and bytestrings, |
|
631 | # ensure that stream does not get a mix of unicode and bytestrings, | |
635 | # or it will cause trouble. |
|
632 | # or it will cause trouble. | |
636 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
633 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
637 | self.max_width, unicode_to_str(self.newline), |
|
634 | self.max_width, unicode_to_str(self.newline), | |
638 | singleton_pprinters=self.singleton_printers, |
|
635 | singleton_pprinters=self.singleton_printers, | |
639 | type_pprinters=self.type_printers, |
|
636 | type_pprinters=self.type_printers, | |
640 | deferred_pprinters=self.deferred_printers) |
|
637 | deferred_pprinters=self.deferred_printers) | |
641 | printer.pretty(obj) |
|
638 | printer.pretty(obj) | |
642 | printer.flush() |
|
639 | printer.flush() | |
643 | return stream.getvalue() |
|
640 | return stream.getvalue() | |
644 |
|
641 | |||
645 |
|
642 | |||
646 | class HTMLFormatter(BaseFormatter): |
|
643 | class HTMLFormatter(BaseFormatter): | |
647 | """An HTML formatter. |
|
644 | """An HTML formatter. | |
648 |
|
645 | |||
649 | To define the callables that compute the HTML representation of your |
|
646 | To define the callables that compute the HTML representation of your | |
650 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
647 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` | |
651 | or :meth:`for_type_by_name` methods to register functions that handle |
|
648 | or :meth:`for_type_by_name` methods to register functions that handle | |
652 | this. |
|
649 | this. | |
653 |
|
650 | |||
654 | The return value of this formatter should be a valid HTML snippet that |
|
651 | The return value of this formatter should be a valid HTML snippet that | |
655 | could be injected into an existing DOM. It should *not* include the |
|
652 | could be injected into an existing DOM. It should *not* include the | |
656 | ```<html>`` or ```<body>`` tags. |
|
653 | ```<html>`` or ```<body>`` tags. | |
657 | """ |
|
654 | """ | |
658 | format_type = Unicode('text/html') |
|
655 | format_type = Unicode('text/html') | |
659 |
|
656 | |||
660 | print_method = ObjectName('_repr_html_') |
|
657 | print_method = ObjectName('_repr_html_') | |
661 |
|
658 | |||
662 |
|
659 | |||
663 | class SVGFormatter(BaseFormatter): |
|
660 | class SVGFormatter(BaseFormatter): | |
664 | """An SVG formatter. |
|
661 | """An SVG formatter. | |
665 |
|
662 | |||
666 | To define the callables that compute the SVG representation of your |
|
663 | To define the callables that compute the SVG representation of your | |
667 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
664 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` | |
668 | or :meth:`for_type_by_name` methods to register functions that handle |
|
665 | or :meth:`for_type_by_name` methods to register functions that handle | |
669 | this. |
|
666 | this. | |
670 |
|
667 | |||
671 | The return value of this formatter should be valid SVG enclosed in |
|
668 | The return value of this formatter should be valid SVG enclosed in | |
672 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
669 | ```<svg>``` tags, that could be injected into an existing DOM. It should | |
673 | *not* include the ```<html>`` or ```<body>`` tags. |
|
670 | *not* include the ```<html>`` or ```<body>`` tags. | |
674 | """ |
|
671 | """ | |
675 | format_type = Unicode('image/svg+xml') |
|
672 | format_type = Unicode('image/svg+xml') | |
676 |
|
673 | |||
677 | print_method = ObjectName('_repr_svg_') |
|
674 | print_method = ObjectName('_repr_svg_') | |
678 |
|
675 | |||
679 |
|
676 | |||
680 | class PNGFormatter(BaseFormatter): |
|
677 | class PNGFormatter(BaseFormatter): | |
681 | """A PNG formatter. |
|
678 | """A PNG formatter. | |
682 |
|
679 | |||
683 | To define the callables that compute the PNG representation of your |
|
680 | To define the callables that compute the PNG representation of your | |
684 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
681 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` | |
685 | or :meth:`for_type_by_name` methods to register functions that handle |
|
682 | or :meth:`for_type_by_name` methods to register functions that handle | |
686 | this. |
|
683 | this. | |
687 |
|
684 | |||
688 | The return value of this formatter should be raw PNG data, *not* |
|
685 | The return value of this formatter should be raw PNG data, *not* | |
689 | base64 encoded. |
|
686 | base64 encoded. | |
690 | """ |
|
687 | """ | |
691 | format_type = Unicode('image/png') |
|
688 | format_type = Unicode('image/png') | |
692 |
|
689 | |||
693 | print_method = ObjectName('_repr_png_') |
|
690 | print_method = ObjectName('_repr_png_') | |
694 |
|
691 | |||
695 | _return_type = (bytes, unicode_type) |
|
692 | _return_type = (bytes, unicode_type) | |
696 |
|
693 | |||
697 |
|
694 | |||
698 | class JPEGFormatter(BaseFormatter): |
|
695 | class JPEGFormatter(BaseFormatter): | |
699 | """A JPEG formatter. |
|
696 | """A JPEG formatter. | |
700 |
|
697 | |||
701 | To define the callables that compute the JPEG representation of your |
|
698 | To define the callables that compute the JPEG representation of your | |
702 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
699 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` | |
703 | or :meth:`for_type_by_name` methods to register functions that handle |
|
700 | or :meth:`for_type_by_name` methods to register functions that handle | |
704 | this. |
|
701 | this. | |
705 |
|
702 | |||
706 | The return value of this formatter should be raw JPEG data, *not* |
|
703 | The return value of this formatter should be raw JPEG data, *not* | |
707 | base64 encoded. |
|
704 | base64 encoded. | |
708 | """ |
|
705 | """ | |
709 | format_type = Unicode('image/jpeg') |
|
706 | format_type = Unicode('image/jpeg') | |
710 |
|
707 | |||
711 | print_method = ObjectName('_repr_jpeg_') |
|
708 | print_method = ObjectName('_repr_jpeg_') | |
712 |
|
709 | |||
713 | _return_type = (bytes, unicode_type) |
|
710 | _return_type = (bytes, unicode_type) | |
714 |
|
711 | |||
715 |
|
712 | |||
716 | class LatexFormatter(BaseFormatter): |
|
713 | class LatexFormatter(BaseFormatter): | |
717 | """A LaTeX formatter. |
|
714 | """A LaTeX formatter. | |
718 |
|
715 | |||
719 | To define the callables that compute the LaTeX representation of your |
|
716 | To define the callables that compute the LaTeX representation of your | |
720 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
717 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` | |
721 | 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 | |
722 | this. |
|
719 | this. | |
723 |
|
720 | |||
724 | The return value of this formatter should be a valid LaTeX equation, |
|
721 | The return value of this formatter should be a valid LaTeX equation, | |
725 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
722 | enclosed in either ```$```, ```$$``` or another LaTeX equation | |
726 | environment. |
|
723 | environment. | |
727 | """ |
|
724 | """ | |
728 | format_type = Unicode('text/latex') |
|
725 | format_type = Unicode('text/latex') | |
729 |
|
726 | |||
730 | print_method = ObjectName('_repr_latex_') |
|
727 | print_method = ObjectName('_repr_latex_') | |
731 |
|
728 | |||
732 |
|
729 | |||
733 | class JSONFormatter(BaseFormatter): |
|
730 | class JSONFormatter(BaseFormatter): | |
734 | """A JSON string formatter. |
|
731 | """A JSON string formatter. | |
735 |
|
732 | |||
736 | To define the callables that compute the JSON string representation of |
|
733 | To define the callables that compute the JSON string representation of | |
737 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
734 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` | |
738 | 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 | |
739 | this. |
|
736 | this. | |
740 |
|
737 | |||
741 | The return value of this formatter should be a valid JSON string. |
|
738 | The return value of this formatter should be a valid JSON string. | |
742 | """ |
|
739 | """ | |
743 | format_type = Unicode('application/json') |
|
740 | format_type = Unicode('application/json') | |
744 |
|
741 | |||
745 | print_method = ObjectName('_repr_json_') |
|
742 | print_method = ObjectName('_repr_json_') | |
746 |
|
743 | |||
747 |
|
744 | |||
748 | class JavascriptFormatter(BaseFormatter): |
|
745 | class JavascriptFormatter(BaseFormatter): | |
749 | """A Javascript formatter. |
|
746 | """A Javascript formatter. | |
750 |
|
747 | |||
751 | To define the callables that compute the Javascript representation of |
|
748 | To define the callables that compute the Javascript representation of | |
752 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
749 | your objects, define a :meth:`_repr_javascript_` method or use the | |
753 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
750 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions | |
754 | that handle this. |
|
751 | that handle this. | |
755 |
|
752 | |||
756 | The return value of this formatter should be valid Javascript code and |
|
753 | The return value of this formatter should be valid Javascript code and | |
757 | should *not* be enclosed in ```<script>``` tags. |
|
754 | should *not* be enclosed in ```<script>``` tags. | |
758 | """ |
|
755 | """ | |
759 | format_type = Unicode('application/javascript') |
|
756 | format_type = Unicode('application/javascript') | |
760 |
|
757 | |||
761 | print_method = ObjectName('_repr_javascript_') |
|
758 | print_method = ObjectName('_repr_javascript_') | |
762 |
|
759 | |||
763 | FormatterABC.register(BaseFormatter) |
|
760 | FormatterABC.register(BaseFormatter) | |
764 | FormatterABC.register(PlainTextFormatter) |
|
761 | FormatterABC.register(PlainTextFormatter) | |
765 | FormatterABC.register(HTMLFormatter) |
|
762 | FormatterABC.register(HTMLFormatter) | |
766 | FormatterABC.register(SVGFormatter) |
|
763 | FormatterABC.register(SVGFormatter) | |
767 | FormatterABC.register(PNGFormatter) |
|
764 | FormatterABC.register(PNGFormatter) | |
768 | FormatterABC.register(JPEGFormatter) |
|
765 | FormatterABC.register(JPEGFormatter) | |
769 | FormatterABC.register(LatexFormatter) |
|
766 | FormatterABC.register(LatexFormatter) | |
770 | FormatterABC.register(JSONFormatter) |
|
767 | FormatterABC.register(JSONFormatter) | |
771 | FormatterABC.register(JavascriptFormatter) |
|
768 | FormatterABC.register(JavascriptFormatter) | |
772 |
|
769 | |||
773 |
|
770 | |||
774 | def format_display_data(obj, include=None, exclude=None): |
|
771 | def format_display_data(obj, include=None, exclude=None): | |
775 | """Return a format data dict for an object. |
|
772 | """Return a format data dict for an object. | |
776 |
|
773 | |||
777 | By default all format types will be computed. |
|
774 | By default all format types will be computed. | |
778 |
|
775 | |||
779 | The following MIME types are currently implemented: |
|
776 | The following MIME types are currently implemented: | |
780 |
|
777 | |||
781 | * text/plain |
|
778 | * text/plain | |
782 | * text/html |
|
779 | * text/html | |
783 | * text/latex |
|
780 | * text/latex | |
784 | * application/json |
|
781 | * application/json | |
785 | * application/javascript |
|
782 | * application/javascript | |
786 | * image/png |
|
783 | * image/png | |
787 | * image/jpeg |
|
784 | * image/jpeg | |
788 | * image/svg+xml |
|
785 | * image/svg+xml | |
789 |
|
786 | |||
790 | Parameters |
|
787 | Parameters | |
791 | ---------- |
|
788 | ---------- | |
792 | obj : object |
|
789 | obj : object | |
793 | The Python object whose format data will be computed. |
|
790 | The Python object whose format data will be computed. | |
794 |
|
791 | |||
795 | Returns |
|
792 | Returns | |
796 | ------- |
|
793 | ------- | |
797 | format_dict : dict |
|
794 | format_dict : dict | |
798 | A dictionary of key/value pairs, one or each format that was |
|
795 | A dictionary of key/value pairs, one or each format that was | |
799 | generated for the object. The keys are the format types, which |
|
796 | generated for the object. The keys are the format types, which | |
800 | will usually be MIME type strings and the values and JSON'able |
|
797 | will usually be MIME type strings and the values and JSON'able | |
801 | data structure containing the raw data for the representation in |
|
798 | data structure containing the raw data for the representation in | |
802 | that format. |
|
799 | that format. | |
803 | include : list or tuple, optional |
|
800 | include : list or tuple, optional | |
804 | A list of format type strings (MIME types) to include in the |
|
801 | A list of format type strings (MIME types) to include in the | |
805 | format data dict. If this is set *only* the format types included |
|
802 | format data dict. If this is set *only* the format types included | |
806 | in this list will be computed. |
|
803 | in this list will be computed. | |
807 | exclude : list or tuple, optional |
|
804 | exclude : list or tuple, optional | |
808 | A list of format type string (MIME types) to exclue in the format |
|
805 | A list of format type string (MIME types) to exclue in the format | |
809 | data dict. If this is set all format types will be computed, |
|
806 | data dict. If this is set all format types will be computed, | |
810 | except for those included in this argument. |
|
807 | except for those included in this argument. | |
811 | """ |
|
808 | """ | |
812 | from IPython.core.interactiveshell import InteractiveShell |
|
809 | from IPython.core.interactiveshell import InteractiveShell | |
813 |
|
810 | |||
814 | InteractiveShell.instance().display_formatter.format( |
|
811 | InteractiveShell.instance().display_formatter.format( | |
815 | obj, |
|
812 | obj, | |
816 | include, |
|
813 | include, | |
817 | exclude |
|
814 | exclude | |
818 | ) |
|
815 | ) | |
819 |
|
816 |
General Comments 0
You need to be logged in to leave comments.
Login now