##// END OF EJS Templates
Addressing review comments....
Brian Granger -
Show More
@@ -1,117 +1,118 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats.
3 3
4 4 Authors:
5 5
6 6 * Brian Granger
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2008-2010 The IPython Development Team
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Main functions
22 22 #-----------------------------------------------------------------------------
23 23
24 24 def display(obj, include=None, exclude=None):
25 25 """Display a Python object in all frontends.
26 26
27 27 By default all representations will be computed and sent to the frontends.
28 28 Frontends can decide which representation is used and how.
29 29
30 30 Parameters
31 31 ----------
32 32 obj : object
33 33 The Python object to display.
34 34 include : list or tuple, optional
35 35 A list of format type strings (MIME types) to include in the
36 36 format data dict. If this is set *only* the format types included
37 37 in this list will be computed.
38 38 exclude : list or tuple, optional
39 39 A list of format type string (MIME types) to exclue in the format
40 40 data dict. If this is set all format types will be computed,
41 41 except for those included in this argument.
42 42 """
43 43 from IPython.core.interactiveshell import InteractiveShell
44 format = InteractiveShell.instance().display_formatter.format
45 publish = InteractiveShell.instance().display_pub.publish
44 inst = InteractiveShell.instance()
45 format = inst.display_formatter.format
46 publish = inst.display_pub.publish
46 47
47 48 format_dict = format(obj, include=include, exclude=exclude)
48 49 publish('IPython.core.display.display', format_dict)
49 50
50 51
51 52 def display_pretty(obj):
52 53 """Display the pretty (default) representation of an object.
53 54
54 55 Parameters
55 56 ----------
56 57 obj : object
57 58 The Python object to display.
58 59 """
59 60 display(obj, include=['text/plain'])
60 61
61 62
62 63 def display_html(obj):
63 64 """Display the HTML representation of an object.
64 65
65 66 Parameters
66 67 ----------
67 68 obj : object
68 69 The Python object to display.
69 70 """
70 71 display(obj, include=['text/plain','text/html'])
71 72
72 73
73 74 def display_svg(obj):
74 75 """Display the SVG representation of an object.
75 76
76 77 Parameters
77 78 ----------
78 79 obj : object
79 80 The Python object to display.
80 81 """
81 82 display(obj, include=['text/plain','image/svg+xml'])
82 83
83 84
84 85 def display_png(obj):
85 86 """Display the PNG representation of an object.
86 87
87 88 Parameters
88 89 ----------
89 90 obj : object
90 91 The Python object to display.
91 92 """
92 93 display(obj, include=['text/plain','image/png'])
93 94
94 95
95 96 def display_latex(obj):
96 97 """Display the LaTeX representation of an object.
97 98
98 99 Parameters
99 100 ----------
100 101 obj : object
101 102 The Python object to display.
102 103 """
103 104 display(obj, include=['text/plain','text/latex'])
104 105
105 106
106 107 def display_json(obj):
107 108 """Display the JSON representation of an object.
108 109
109 110 Parameters
110 111 ----------
111 112 obj : object
112 113 The Python object to display.
113 114 """
114 115 display(obj, include=['text/plain','application/json'])
115 116
116 117
117 118
@@ -1,322 +1,322 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 This defines a callable class that IPython uses for `sys.displayhook`.
5 5
6 6 Authors:
7 7
8 8 * Fernando Perez
9 9 * Brian Granger
10 10 * Robert Kern
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Copyright (C) 2008-2010 The IPython Development Team
15 15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 import __builtin__
26 26
27 27 from IPython.config.configurable import Configurable
28 28 from IPython.core import prompts
29 29 import IPython.utils.generics
30 30 import IPython.utils.io
31 31 from IPython.utils.traitlets import Instance, List
32 32 from IPython.utils.warn import warn
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Main displayhook class
36 36 #-----------------------------------------------------------------------------
37 37
38 38 # TODO: The DisplayHook class should be split into two classes, one that
39 39 # manages the prompts and their synchronization and another that just does the
40 40 # displayhook logic and calls into the prompt manager.
41 41
42 42 # TODO: Move the various attributes (cache_size, colors, input_sep,
43 43 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
44 44 # attributes of InteractiveShell. They should be on ONE object only and the
45 45 # other objects should ask that one object for their values.
46 46
47 47 class DisplayHook(Configurable):
48 48 """The custom IPython displayhook to replace sys.displayhook.
49 49
50 50 This class does many things, but the basic idea is that it is a callable
51 51 that gets called anytime user code returns a value.
52 52
53 53 Currently this class does more than just the displayhook logic and that
54 54 extra logic should eventually be moved out of here.
55 55 """
56 56
57 57 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
58 58
59 59 def __init__(self, shell=None, cache_size=1000,
60 60 colors='NoColor', input_sep='\n',
61 61 output_sep='\n', output_sep2='',
62 62 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
63 63 config=None):
64 64 super(DisplayHook, self).__init__(shell=shell, config=config)
65 65
66 66 cache_size_min = 3
67 67 if cache_size <= 0:
68 68 self.do_full_cache = 0
69 69 cache_size = 0
70 70 elif cache_size < cache_size_min:
71 71 self.do_full_cache = 0
72 72 cache_size = 0
73 73 warn('caching was disabled (min value for cache size is %s).' %
74 74 cache_size_min,level=3)
75 75 else:
76 76 self.do_full_cache = 1
77 77
78 78 self.cache_size = cache_size
79 79 self.input_sep = input_sep
80 80
81 81 # we need a reference to the user-level namespace
82 82 self.shell = shell
83 83
84 84 # Set input prompt strings and colors
85 85 if cache_size == 0:
86 86 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
87 87 or ps1.find(r'\N') > -1:
88 88 ps1 = '>>> '
89 89 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
90 90 or ps2.find(r'\N') > -1:
91 91 ps2 = '... '
92 92 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
93 93 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
94 94 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
95 95
96 96 self.color_table = prompts.PromptColors
97 97 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
98 98 pad_left=pad_left)
99 99 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
100 100 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
101 101 pad_left=pad_left)
102 102 self.set_colors(colors)
103 103
104 104 # Store the last prompt string each time, we need it for aligning
105 105 # continuation and auto-rewrite prompts
106 106 self.last_prompt = ''
107 107 self.output_sep = output_sep
108 108 self.output_sep2 = output_sep2
109 109 self._,self.__,self.___ = '','',''
110 110
111 111 # these are deliberately global:
112 112 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
113 113 self.shell.user_ns.update(to_user_ns)
114 114
115 115 @property
116 116 def prompt_count(self):
117 117 return self.shell.execution_count
118 118
119 119 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
120 120 if p_str is None:
121 121 if self.do_full_cache:
122 122 return cache_def
123 123 else:
124 124 return no_cache_def
125 125 else:
126 126 return p_str
127 127
128 128 def set_colors(self, colors):
129 129 """Set the active color scheme and configure colors for the three
130 130 prompt subsystems."""
131 131
132 132 # FIXME: This modifying of the global prompts.prompt_specials needs
133 133 # to be fixed. We need to refactor all of the prompts stuff to use
134 134 # proper configuration and traits notifications.
135 135 if colors.lower()=='nocolor':
136 136 prompts.prompt_specials = prompts.prompt_specials_nocolor
137 137 else:
138 138 prompts.prompt_specials = prompts.prompt_specials_color
139 139
140 140 self.color_table.set_active_scheme(colors)
141 141 self.prompt1.set_colors()
142 142 self.prompt2.set_colors()
143 143 self.prompt_out.set_colors()
144 144
145 145 #-------------------------------------------------------------------------
146 146 # Methods used in __call__. Override these methods to modify the behavior
147 147 # of the displayhook.
148 148 #-------------------------------------------------------------------------
149 149
150 150 def check_for_underscore(self):
151 151 """Check if the user has set the '_' variable by hand."""
152 152 # If something injected a '_' variable in __builtin__, delete
153 153 # ipython's automatic one so we don't clobber that. gettext() in
154 154 # particular uses _, so we need to stay away from it.
155 155 if '_' in __builtin__.__dict__:
156 156 try:
157 157 del self.shell.user_ns['_']
158 158 except KeyError:
159 159 pass
160 160
161 161 def quiet(self):
162 162 """Should we silence the display hook because of ';'?"""
163 163 # do not print output if input ends in ';'
164 164 try:
165 165 if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'):
166 166 return True
167 167 except IndexError:
168 168 # some uses of ipshellembed may fail here
169 169 pass
170 170 return False
171 171
172 172 def start_displayhook(self):
173 173 """Start the displayhook, initializing resources."""
174 174 pass
175 175
176 176 def write_output_prompt(self):
177 177 """Write the output prompt.
178 178
179 179 The default implementation simply writes the prompt to
180 180 ``io.Term.cout``.
181 181 """
182 182 # Use write, not print which adds an extra space.
183 183 IPython.utils.io.Term.cout.write(self.output_sep)
184 184 outprompt = str(self.prompt_out)
185 185 if self.do_full_cache:
186 186 IPython.utils.io.Term.cout.write(outprompt)
187 187
188 188 def compute_format_data(self, result):
189 189 """Compute format data of the object to be displayed.
190 190
191 191 The format data is a generalization of the :func:`repr` of an object.
192 192 In the default implementation the format data is a :class:`dict` of
193 193 key value pair where the keys are valid MIME types and the values
194 194 are JSON'able data structure containing the raw data for that MIME
195 195 type. It is up to frontends to determine pick a MIME to to use and
196 196 display that data in an appropriate manner.
197 197
198 This method only compute the format data for the object and should NOT
199 actually print or write that to a stream.
198 This method only computes the format data for the object and should
199 NOT actually print or write that to a stream.
200 200
201 201 Parameters
202 202 ----------
203 203 result : object
204 The Python object passed to the display hook, whose forat will be
204 The Python object passed to the display hook, whose format will be
205 205 computed.
206 206
207 207 Returns
208 208 -------
209 209 format_data : dict
210 210 A :class:`dict` whose keys are valid MIME types and values are
211 211 JSON'able raw data for that MIME type. It is recommended that
212 212 all return values of this should always include the "text/plain"
213 213 MIME type representation of the object.
214 214 """
215 215 format_dict = self.shell.display_formatter.format(result)
216 216 return format_dict
217 217
218 218 def write_format_data(self, format_dict):
219 219 """Write the format data dict to the frontend.
220 220
221 221 This default version of this method simply writes the plain text
222 222 representation of the object to ``io.Term.cout``. Subclasses should
223 223 override this method to send the entire `format_dict` to the
224 224 frontends.
225 225
226 226 Parameters
227 227 ----------
228 228 format_dict : dict
229 229 The format dict for the object passed to `sys.displayhook`.
230 230 """
231 231 # We want to print because we want to always make sure we have a
232 232 # newline, even if all the prompt separators are ''. This is the
233 233 # standard IPython behavior.
234 234 result_repr = format_dict['text/plain']
235 235 if '\n' in result_repr:
236 236 # So that multi-line strings line up with the left column of
237 237 # the screen, instead of having the output prompt mess up
238 238 # their first line.
239 239 # We use the ps_out_str template instead of the expanded prompt
240 240 # because the expansion may add ANSI escapes that will interfere
241 241 # with our ability to determine whether or not we should add
242 242 # a newline.
243 243 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
244 244 # But avoid extraneous empty lines.
245 245 result_repr = '\n' + result_repr
246 246
247 247 print >>IPython.utils.io.Term.cout, result_repr
248 248
249 249 def update_user_ns(self, result):
250 250 """Update user_ns with various things like _, __, _1, etc."""
251 251
252 252 # Avoid recursive reference when displaying _oh/Out
253 253 if result is not self.shell.user_ns['_oh']:
254 254 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
255 255 warn('Output cache limit (currently '+
256 256 `self.cache_size`+' entries) hit.\n'
257 257 'Flushing cache and resetting history counter...\n'
258 258 'The only history variables available will be _,__,___ and _1\n'
259 259 'with the current result.')
260 260
261 261 self.flush()
262 262 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
263 263 # we cause buggy behavior for things like gettext).
264 264 if '_' not in __builtin__.__dict__:
265 265 self.___ = self.__
266 266 self.__ = self._
267 267 self._ = result
268 268 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
269 269
270 270 # hackish access to top-level namespace to create _1,_2... dynamically
271 271 to_main = {}
272 272 if self.do_full_cache:
273 273 new_result = '_'+`self.prompt_count`
274 274 to_main[new_result] = result
275 275 self.shell.user_ns.update(to_main)
276 276 self.shell.user_ns['_oh'][self.prompt_count] = result
277 277
278 278 def log_output(self, result):
279 279 """Log the output."""
280 280 if self.shell.logger.log_output:
281 281 self.shell.logger.log_write(repr(result), 'output')
282 282
283 283 def finish_displayhook(self):
284 284 """Finish up all displayhook activities."""
285 285 IPython.utils.io.Term.cout.write(self.output_sep2)
286 286 IPython.utils.io.Term.cout.flush()
287 287
288 288 def __call__(self, result=None):
289 289 """Printing with history cache management.
290 290
291 291 This is invoked everytime the interpreter needs to print, and is
292 292 activated by setting the variable sys.displayhook to it.
293 293 """
294 294 self.check_for_underscore()
295 295 if result is not None and not self.quiet():
296 296 self.start_displayhook()
297 297 self.write_output_prompt()
298 298 format_dict = self.compute_format_data(result)
299 299 self.write_format_data(format_dict)
300 300 self.update_user_ns(result)
301 301 self.log_output(result)
302 302 self.finish_displayhook()
303 303
304 304 def flush(self):
305 305 if not self.do_full_cache:
306 306 raise ValueError,"You shouldn't have reached the cache flush "\
307 307 "if full caching is not enabled!"
308 308 # delete auto-generated vars from global namespace
309 309
310 310 for n in range(1,self.prompt_count + 1):
311 311 key = '_'+`n`
312 312 try:
313 313 del self.shell.user_ns[key]
314 314 except: pass
315 315 self.shell.user_ns['_oh'].clear()
316 316
317 317 if '_' not in __builtin__.__dict__:
318 318 self.shell.user_ns.update({'_':None,'__':None, '___':None})
319 319 import gc
320 320 # TODO: Is this really needed?
321 321 gc.collect()
322 322
@@ -1,143 +1,145 b''
1 1 """An interface for publishing rich data to frontends.
2 2
3 3 There are two components of the display system:
4 4
5 5 * Display formatters, which take a Python object and compute the
6 6 representation of the object in various formats (text, HTML, SVg, etc.).
7 7 * The display publisher that is used to send the representation data to the
8 8 various frontends.
9 9
10 10 This module defines the logic display publishing. The display publisher uses
11 11 the ``display_data`` message type that is defined in the IPython messaging
12 12 spec.
13 13
14 14 Authors:
15 15
16 16 * Brian Granger
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008-2010 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Imports
28 28 #-----------------------------------------------------------------------------
29 29
30 from __future__ import print_function
31
30 32 from IPython.config.configurable import Configurable
31 33
32 34 #-----------------------------------------------------------------------------
33 35 # Main payload class
34 36 #-----------------------------------------------------------------------------
35 37
36 38 class DisplayPublisher(Configurable):
37 39 """A traited class that publishes display data to frontends.
38 40
39 41 Instances of this class are created by the main IPython object and should
40 42 be accessed there.
41 43 """
42 44
43 45 def _validate_data(self, source, data, metadata=None):
44 46 """Validate the display data.
45 47
46 48 Parameters
47 49 ----------
48 50 source : str
49 51 The fully dotted name of the callable that created the data, like
50 52 :func:`foo.bar.my_formatter`.
51 53 data : dict
52 54 The formata data dictionary.
53 55 metadata : dict
54 56 Any metadata for the data.
55 57 """
56 58
57 59 if not isinstance(source, str):
58 60 raise TypeError('source must be a str, got: %r' % source)
59 61 if not isinstance(data, dict):
60 62 raise TypeError('data must be a dict, got: %r' % data)
61 63 if metadata is not None:
62 64 if not isinstance(metadata, dict):
63 65 raise TypeError('metadata must be a dict, got: %r' % data)
64 66
65 67 def publish(self, source, data, metadata=None):
66 68 """Publish data and metadata to all frontends.
67 69
68 70 See the ``display_data`` message in the messaging documentation for
69 71 more details about this message type.
70 72
71 73 The following MIME types are currently implemented:
72 74
73 75 * text/plain
74 76 * text/html
75 77 * text/latex
76 78 * application/json
77 79 * image/png
78 80 * immage/svg+xml
79 81
80 82 Parameters
81 83 ----------
82 84 source : str
83 85 A string that give the function or method that created the data,
84 86 such as 'IPython.core.page'.
85 87 data : dict
86 88 A dictionary having keys that are valid MIME types (like
87 89 'text/plain' or 'image/svg+xml') and values that are the data for
88 90 that MIME type. The data itself must be a JSON'able data
89 91 structure. Minimally all data should have the 'text/plain' data,
90 92 which can be displayed by all frontends. If more than the plain
91 93 text is given, it is up to the frontend to decide which
92 94 representation to use.
93 95 metadata : dict
94 96 A dictionary for metadata related to the data. This can contain
95 97 arbitrary key, value pairs that frontends can use to interpret
96 98 the data.
97 99 """
98 100 from IPython.utils import io
99 101 # The default is to simply write the plain text data using io.Term.
100 102 if data.has_key('text/plain'):
101 print >>io.Term.cout, data['text/plain']
103 print(data['text/plain'], file=io.Term.cout)
102 104
103 105
104 106 def publish_display_data(self, source, data, metadata=None):
105 107 """Publish data and metadata to all frontends.
106 108
107 109 See the ``display_data`` message in the messaging documentation for
108 110 more details about this message type.
109 111
110 112 The following MIME types are currently implemented:
111 113
112 114 * text/plain
113 115 * text/html
114 116 * text/latex
115 117 * application/json
116 118 * image/png
117 119 * immage/svg+xml
118 120
119 121 Parameters
120 122 ----------
121 123 source : str
122 124 A string that give the function or method that created the data,
123 125 such as 'IPython.core.page'.
124 126 data : dict
125 127 A dictionary having keys that are valid MIME types (like
126 128 'text/plain' or 'image/svg+xml') and values that are the data for
127 129 that MIME type. The data itself must be a JSON'able data
128 130 structure. Minimally all data should have the 'text/plain' data,
129 131 which can be displayed by all frontends. If more than the plain
130 132 text is given, it is up to the frontend to decide which
131 133 representation to use.
132 134 metadata : dict
133 135 A dictionary for metadata related to the data. This can contain
134 136 arbitrary key, value pairs that frontends can use to interpret
135 137 the data.
136 138 """
137 139 from IPython.core.interactiveshell import InteractiveShell
138 140 InteractiveShell.instance().display_pub.publish(
139 141 source,
140 142 data,
141 143 metadata
142 144 )
143 145
General Comments 0
You need to be logged in to leave comments. Login now