##// END OF EJS Templates
Change functions,...
Srinivas Reddy Thatiparthy -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,103 +1,103 b''
1 """
1 """
2 A context manager for managing things injected into :mod:`__builtin__`.
2 A context manager for managing things injected into :mod:`__builtin__`.
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 * Fernando Perez
7 * Fernando Perez
8 """
8 """
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010-2011 The IPython Development Team.
10 # Copyright (C) 2010-2011 The IPython Development Team.
11 #
11 #
12 # Distributed under the terms of the BSD License.
12 # Distributed under the terms of the BSD License.
13 #
13 #
14 # Complete license in the file COPYING.txt, distributed with this software.
14 # Complete license in the file COPYING.txt, distributed with this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22
22
23 from IPython.utils.py3compat import builtin_mod, iteritems
23 from IPython.utils.py3compat import builtin_mod
24 from traitlets import Instance
24 from traitlets import Instance
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes and functions
27 # Classes and functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class __BuiltinUndefined(object): pass
30 class __BuiltinUndefined(object): pass
31 BuiltinUndefined = __BuiltinUndefined()
31 BuiltinUndefined = __BuiltinUndefined()
32
32
33 class __HideBuiltin(object): pass
33 class __HideBuiltin(object): pass
34 HideBuiltin = __HideBuiltin()
34 HideBuiltin = __HideBuiltin()
35
35
36
36
37 class BuiltinTrap(Configurable):
37 class BuiltinTrap(Configurable):
38
38
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
40 allow_none=True)
40 allow_none=True)
41
41
42 def __init__(self, shell=None):
42 def __init__(self, shell=None):
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
44 self._orig_builtins = {}
44 self._orig_builtins = {}
45 # We define this to track if a single BuiltinTrap is nested.
45 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
46 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
47 self._nested_level = 0
48 self.shell = shell
48 self.shell = shell
49 # builtins we always add - if set to HideBuiltin, they will just
49 # builtins we always add - if set to HideBuiltin, they will just
50 # be removed instead of being replaced by something else
50 # be removed instead of being replaced by something else
51 self.auto_builtins = {'exit': HideBuiltin,
51 self.auto_builtins = {'exit': HideBuiltin,
52 'quit': HideBuiltin,
52 'quit': HideBuiltin,
53 'get_ipython': self.shell.get_ipython,
53 'get_ipython': self.shell.get_ipython,
54 }
54 }
55
55
56 def __enter__(self):
56 def __enter__(self):
57 if self._nested_level == 0:
57 if self._nested_level == 0:
58 self.activate()
58 self.activate()
59 self._nested_level += 1
59 self._nested_level += 1
60 # I return self, so callers can use add_builtin in a with clause.
60 # I return self, so callers can use add_builtin in a with clause.
61 return self
61 return self
62
62
63 def __exit__(self, type, value, traceback):
63 def __exit__(self, type, value, traceback):
64 if self._nested_level == 1:
64 if self._nested_level == 1:
65 self.deactivate()
65 self.deactivate()
66 self._nested_level -= 1
66 self._nested_level -= 1
67 # Returning False will cause exceptions to propagate
67 # Returning False will cause exceptions to propagate
68 return False
68 return False
69
69
70 def add_builtin(self, key, value):
70 def add_builtin(self, key, value):
71 """Add a builtin and save the original."""
71 """Add a builtin and save the original."""
72 bdict = builtin_mod.__dict__
72 bdict = builtin_mod.__dict__
73 orig = bdict.get(key, BuiltinUndefined)
73 orig = bdict.get(key, BuiltinUndefined)
74 if value is HideBuiltin:
74 if value is HideBuiltin:
75 if orig is not BuiltinUndefined: #same as 'key in bdict'
75 if orig is not BuiltinUndefined: #same as 'key in bdict'
76 self._orig_builtins[key] = orig
76 self._orig_builtins[key] = orig
77 del bdict[key]
77 del bdict[key]
78 else:
78 else:
79 self._orig_builtins[key] = orig
79 self._orig_builtins[key] = orig
80 bdict[key] = value
80 bdict[key] = value
81
81
82 def remove_builtin(self, key, orig):
82 def remove_builtin(self, key, orig):
83 """Remove an added builtin and re-set the original."""
83 """Remove an added builtin and re-set the original."""
84 if orig is BuiltinUndefined:
84 if orig is BuiltinUndefined:
85 del builtin_mod.__dict__[key]
85 del builtin_mod.__dict__[key]
86 else:
86 else:
87 builtin_mod.__dict__[key] = orig
87 builtin_mod.__dict__[key] = orig
88
88
89 def activate(self):
89 def activate(self):
90 """Store ipython references in the __builtin__ namespace."""
90 """Store ipython references in the __builtin__ namespace."""
91
91
92 add_builtin = self.add_builtin
92 add_builtin = self.add_builtin
93 for name, func in iteritems(self.auto_builtins):
93 for name, func in self.auto_builtins.items():
94 add_builtin(name, func)
94 add_builtin(name, func)
95
95
96 def deactivate(self):
96 def deactivate(self):
97 """Remove any builtins which might have been added by add_builtins, or
97 """Remove any builtins which might have been added by add_builtins, or
98 restore overwritten ones to their previous values."""
98 restore overwritten ones to their previous values."""
99 remove_builtin = self.remove_builtin
99 remove_builtin = self.remove_builtin
100 for key, val in iteritems(self._orig_builtins):
100 for key, val in self._orig_builtins.items():
101 remove_builtin(key, val)
101 remove_builtin(key, val)
102 self._orig_builtins.clear()
102 self._orig_builtins.clear()
103 self._builtins_added = False
103 self._builtins_added = False
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,679 +1,679 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 import os
14 import os
15 import re
15 import re
16 import sys
16 import sys
17 import types
17 import types
18 from getopt import getopt, GetoptError
18 from getopt import getopt, GetoptError
19
19
20 from traitlets.config.configurable import Configurable
20 from traitlets.config.configurable import Configurable
21 from IPython.core import oinspect
21 from IPython.core import oinspect
22 from IPython.core.error import UsageError
22 from IPython.core.error import UsageError
23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
23 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
24 from decorator import decorator
24 from decorator import decorator
25 from IPython.utils.ipstruct import Struct
25 from IPython.utils.ipstruct import Struct
26 from IPython.utils.process import arg_split
26 from IPython.utils.process import arg_split
27 from IPython.utils.py3compat import string_types, iteritems
27 from IPython.utils.py3compat import string_types
28 from IPython.utils.text import dedent
28 from IPython.utils.text import dedent
29 from traitlets import Bool, Dict, Instance, observe
29 from traitlets import Bool, Dict, Instance, observe
30 from logging import error
30 from logging import error
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Globals
33 # Globals
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 # A dict we'll use for each class that has magics, used as temporary storage to
36 # A dict we'll use for each class that has magics, used as temporary storage to
37 # pass information between the @line/cell_magic method decorators and the
37 # pass information between the @line/cell_magic method decorators and the
38 # @magics_class class decorator, because the method decorators have no
38 # @magics_class class decorator, because the method decorators have no
39 # access to the class when they run. See for more details:
39 # access to the class when they run. See for more details:
40 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
40 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
41
41
42 magics = dict(line={}, cell={})
42 magics = dict(line={}, cell={})
43
43
44 magic_kinds = ('line', 'cell')
44 magic_kinds = ('line', 'cell')
45 magic_spec = ('line', 'cell', 'line_cell')
45 magic_spec = ('line', 'cell', 'line_cell')
46 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
46 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
47
47
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49 # Utility classes and functions
49 # Utility classes and functions
50 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
51
51
52 class Bunch: pass
52 class Bunch: pass
53
53
54
54
55 def on_off(tag):
55 def on_off(tag):
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 return ['OFF','ON'][tag]
57 return ['OFF','ON'][tag]
58
58
59
59
60 def compress_dhist(dh):
60 def compress_dhist(dh):
61 """Compress a directory history into a new one with at most 20 entries.
61 """Compress a directory history into a new one with at most 20 entries.
62
62
63 Return a new list made from the first and last 10 elements of dhist after
63 Return a new list made from the first and last 10 elements of dhist after
64 removal of duplicates.
64 removal of duplicates.
65 """
65 """
66 head, tail = dh[:-10], dh[-10:]
66 head, tail = dh[:-10], dh[-10:]
67
67
68 newhead = []
68 newhead = []
69 done = set()
69 done = set()
70 for h in head:
70 for h in head:
71 if h in done:
71 if h in done:
72 continue
72 continue
73 newhead.append(h)
73 newhead.append(h)
74 done.add(h)
74 done.add(h)
75
75
76 return newhead + tail
76 return newhead + tail
77
77
78
78
79 def needs_local_scope(func):
79 def needs_local_scope(func):
80 """Decorator to mark magic functions which need to local scope to run."""
80 """Decorator to mark magic functions which need to local scope to run."""
81 func.needs_local_scope = True
81 func.needs_local_scope = True
82 return func
82 return func
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 # Class and method decorators for registering magics
85 # Class and method decorators for registering magics
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87
87
88 def magics_class(cls):
88 def magics_class(cls):
89 """Class decorator for all subclasses of the main Magics class.
89 """Class decorator for all subclasses of the main Magics class.
90
90
91 Any class that subclasses Magics *must* also apply this decorator, to
91 Any class that subclasses Magics *must* also apply this decorator, to
92 ensure that all the methods that have been decorated as line/cell magics
92 ensure that all the methods that have been decorated as line/cell magics
93 get correctly registered in the class instance. This is necessary because
93 get correctly registered in the class instance. This is necessary because
94 when method decorators run, the class does not exist yet, so they
94 when method decorators run, the class does not exist yet, so they
95 temporarily store their information into a module global. Application of
95 temporarily store their information into a module global. Application of
96 this class decorator copies that global data to the class instance and
96 this class decorator copies that global data to the class instance and
97 clears the global.
97 clears the global.
98
98
99 Obviously, this mechanism is not thread-safe, which means that the
99 Obviously, this mechanism is not thread-safe, which means that the
100 *creation* of subclasses of Magic should only be done in a single-thread
100 *creation* of subclasses of Magic should only be done in a single-thread
101 context. Instantiation of the classes has no restrictions. Given that
101 context. Instantiation of the classes has no restrictions. Given that
102 these classes are typically created at IPython startup time and before user
102 these classes are typically created at IPython startup time and before user
103 application code becomes active, in practice this should not pose any
103 application code becomes active, in practice this should not pose any
104 problems.
104 problems.
105 """
105 """
106 cls.registered = True
106 cls.registered = True
107 cls.magics = dict(line = magics['line'],
107 cls.magics = dict(line = magics['line'],
108 cell = magics['cell'])
108 cell = magics['cell'])
109 magics['line'] = {}
109 magics['line'] = {}
110 magics['cell'] = {}
110 magics['cell'] = {}
111 return cls
111 return cls
112
112
113
113
114 def record_magic(dct, magic_kind, magic_name, func):
114 def record_magic(dct, magic_kind, magic_name, func):
115 """Utility function to store a function as a magic of a specific kind.
115 """Utility function to store a function as a magic of a specific kind.
116
116
117 Parameters
117 Parameters
118 ----------
118 ----------
119 dct : dict
119 dct : dict
120 A dictionary with 'line' and 'cell' subdicts.
120 A dictionary with 'line' and 'cell' subdicts.
121
121
122 magic_kind : str
122 magic_kind : str
123 Kind of magic to be stored.
123 Kind of magic to be stored.
124
124
125 magic_name : str
125 magic_name : str
126 Key to store the magic as.
126 Key to store the magic as.
127
127
128 func : function
128 func : function
129 Callable object to store.
129 Callable object to store.
130 """
130 """
131 if magic_kind == 'line_cell':
131 if magic_kind == 'line_cell':
132 dct['line'][magic_name] = dct['cell'][magic_name] = func
132 dct['line'][magic_name] = dct['cell'][magic_name] = func
133 else:
133 else:
134 dct[magic_kind][magic_name] = func
134 dct[magic_kind][magic_name] = func
135
135
136
136
137 def validate_type(magic_kind):
137 def validate_type(magic_kind):
138 """Ensure that the given magic_kind is valid.
138 """Ensure that the given magic_kind is valid.
139
139
140 Check that the given magic_kind is one of the accepted spec types (stored
140 Check that the given magic_kind is one of the accepted spec types (stored
141 in the global `magic_spec`), raise ValueError otherwise.
141 in the global `magic_spec`), raise ValueError otherwise.
142 """
142 """
143 if magic_kind not in magic_spec:
143 if magic_kind not in magic_spec:
144 raise ValueError('magic_kind must be one of %s, %s given' %
144 raise ValueError('magic_kind must be one of %s, %s given' %
145 magic_kinds, magic_kind)
145 magic_kinds, magic_kind)
146
146
147
147
148 # The docstrings for the decorator below will be fairly similar for the two
148 # The docstrings for the decorator below will be fairly similar for the two
149 # types (method and function), so we generate them here once and reuse the
149 # types (method and function), so we generate them here once and reuse the
150 # templates below.
150 # templates below.
151 _docstring_template = \
151 _docstring_template = \
152 """Decorate the given {0} as {1} magic.
152 """Decorate the given {0} as {1} magic.
153
153
154 The decorator can be used with or without arguments, as follows.
154 The decorator can be used with or without arguments, as follows.
155
155
156 i) without arguments: it will create a {1} magic named as the {0} being
156 i) without arguments: it will create a {1} magic named as the {0} being
157 decorated::
157 decorated::
158
158
159 @deco
159 @deco
160 def foo(...)
160 def foo(...)
161
161
162 will create a {1} magic named `foo`.
162 will create a {1} magic named `foo`.
163
163
164 ii) with one string argument: which will be used as the actual name of the
164 ii) with one string argument: which will be used as the actual name of the
165 resulting magic::
165 resulting magic::
166
166
167 @deco('bar')
167 @deco('bar')
168 def foo(...)
168 def foo(...)
169
169
170 will create a {1} magic named `bar`.
170 will create a {1} magic named `bar`.
171 """
171 """
172
172
173 # These two are decorator factories. While they are conceptually very similar,
173 # These two are decorator factories. While they are conceptually very similar,
174 # there are enough differences in the details that it's simpler to have them
174 # there are enough differences in the details that it's simpler to have them
175 # written as completely standalone functions rather than trying to share code
175 # written as completely standalone functions rather than trying to share code
176 # and make a single one with convoluted logic.
176 # and make a single one with convoluted logic.
177
177
178 def _method_magic_marker(magic_kind):
178 def _method_magic_marker(magic_kind):
179 """Decorator factory for methods in Magics subclasses.
179 """Decorator factory for methods in Magics subclasses.
180 """
180 """
181
181
182 validate_type(magic_kind)
182 validate_type(magic_kind)
183
183
184 # This is a closure to capture the magic_kind. We could also use a class,
184 # This is a closure to capture the magic_kind. We could also use a class,
185 # but it's overkill for just that one bit of state.
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
186 def magic_deco(arg):
187 call = lambda f, *a, **k: f(*a, **k)
187 call = lambda f, *a, **k: f(*a, **k)
188
188
189 if callable(arg):
189 if callable(arg):
190 # "Naked" decorator call (just @foo, no args)
190 # "Naked" decorator call (just @foo, no args)
191 func = arg
191 func = arg
192 name = func.__name__
192 name = func.__name__
193 retval = decorator(call, func)
193 retval = decorator(call, func)
194 record_magic(magics, magic_kind, name, name)
194 record_magic(magics, magic_kind, name, name)
195 elif isinstance(arg, string_types):
195 elif isinstance(arg, string_types):
196 # Decorator called with arguments (@foo('bar'))
196 # Decorator called with arguments (@foo('bar'))
197 name = arg
197 name = arg
198 def mark(func, *a, **kw):
198 def mark(func, *a, **kw):
199 record_magic(magics, magic_kind, name, func.__name__)
199 record_magic(magics, magic_kind, name, func.__name__)
200 return decorator(call, func)
200 return decorator(call, func)
201 retval = mark
201 retval = mark
202 else:
202 else:
203 raise TypeError("Decorator can only be called with "
203 raise TypeError("Decorator can only be called with "
204 "string or function")
204 "string or function")
205 return retval
205 return retval
206
206
207 # Ensure the resulting decorator has a usable docstring
207 # Ensure the resulting decorator has a usable docstring
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
208 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
209 return magic_deco
209 return magic_deco
210
210
211
211
212 def _function_magic_marker(magic_kind):
212 def _function_magic_marker(magic_kind):
213 """Decorator factory for standalone functions.
213 """Decorator factory for standalone functions.
214 """
214 """
215 validate_type(magic_kind)
215 validate_type(magic_kind)
216
216
217 # This is a closure to capture the magic_kind. We could also use a class,
217 # This is a closure to capture the magic_kind. We could also use a class,
218 # but it's overkill for just that one bit of state.
218 # but it's overkill for just that one bit of state.
219 def magic_deco(arg):
219 def magic_deco(arg):
220 call = lambda f, *a, **k: f(*a, **k)
220 call = lambda f, *a, **k: f(*a, **k)
221
221
222 # Find get_ipython() in the caller's namespace
222 # Find get_ipython() in the caller's namespace
223 caller = sys._getframe(1)
223 caller = sys._getframe(1)
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
225 get_ipython = getattr(caller, ns).get('get_ipython')
225 get_ipython = getattr(caller, ns).get('get_ipython')
226 if get_ipython is not None:
226 if get_ipython is not None:
227 break
227 break
228 else:
228 else:
229 raise NameError('Decorator can only run in context where '
229 raise NameError('Decorator can only run in context where '
230 '`get_ipython` exists')
230 '`get_ipython` exists')
231
231
232 ip = get_ipython()
232 ip = get_ipython()
233
233
234 if callable(arg):
234 if callable(arg):
235 # "Naked" decorator call (just @foo, no args)
235 # "Naked" decorator call (just @foo, no args)
236 func = arg
236 func = arg
237 name = func.__name__
237 name = func.__name__
238 ip.register_magic_function(func, magic_kind, name)
238 ip.register_magic_function(func, magic_kind, name)
239 retval = decorator(call, func)
239 retval = decorator(call, func)
240 elif isinstance(arg, string_types):
240 elif isinstance(arg, string_types):
241 # Decorator called with arguments (@foo('bar'))
241 # Decorator called with arguments (@foo('bar'))
242 name = arg
242 name = arg
243 def mark(func, *a, **kw):
243 def mark(func, *a, **kw):
244 ip.register_magic_function(func, magic_kind, name)
244 ip.register_magic_function(func, magic_kind, name)
245 return decorator(call, func)
245 return decorator(call, func)
246 retval = mark
246 retval = mark
247 else:
247 else:
248 raise TypeError("Decorator can only be called with "
248 raise TypeError("Decorator can only be called with "
249 "string or function")
249 "string or function")
250 return retval
250 return retval
251
251
252 # Ensure the resulting decorator has a usable docstring
252 # Ensure the resulting decorator has a usable docstring
253 ds = _docstring_template.format('function', magic_kind)
253 ds = _docstring_template.format('function', magic_kind)
254
254
255 ds += dedent("""
255 ds += dedent("""
256 Note: this decorator can only be used in a context where IPython is already
256 Note: this decorator can only be used in a context where IPython is already
257 active, so that the `get_ipython()` call succeeds. You can therefore use
257 active, so that the `get_ipython()` call succeeds. You can therefore use
258 it in your startup files loaded after IPython initializes, but *not* in the
258 it in your startup files loaded after IPython initializes, but *not* in the
259 IPython configuration file itself, which is executed before IPython is
259 IPython configuration file itself, which is executed before IPython is
260 fully up and running. Any file located in the `startup` subdirectory of
260 fully up and running. Any file located in the `startup` subdirectory of
261 your configuration profile will be OK in this sense.
261 your configuration profile will be OK in this sense.
262 """)
262 """)
263
263
264 magic_deco.__doc__ = ds
264 magic_deco.__doc__ = ds
265 return magic_deco
265 return magic_deco
266
266
267
267
268 # Create the actual decorators for public use
268 # Create the actual decorators for public use
269
269
270 # These three are used to decorate methods in class definitions
270 # These three are used to decorate methods in class definitions
271 line_magic = _method_magic_marker('line')
271 line_magic = _method_magic_marker('line')
272 cell_magic = _method_magic_marker('cell')
272 cell_magic = _method_magic_marker('cell')
273 line_cell_magic = _method_magic_marker('line_cell')
273 line_cell_magic = _method_magic_marker('line_cell')
274
274
275 # These three decorate standalone functions and perform the decoration
275 # These three decorate standalone functions and perform the decoration
276 # immediately. They can only run where get_ipython() works
276 # immediately. They can only run where get_ipython() works
277 register_line_magic = _function_magic_marker('line')
277 register_line_magic = _function_magic_marker('line')
278 register_cell_magic = _function_magic_marker('cell')
278 register_cell_magic = _function_magic_marker('cell')
279 register_line_cell_magic = _function_magic_marker('line_cell')
279 register_line_cell_magic = _function_magic_marker('line_cell')
280
280
281 #-----------------------------------------------------------------------------
281 #-----------------------------------------------------------------------------
282 # Core Magic classes
282 # Core Magic classes
283 #-----------------------------------------------------------------------------
283 #-----------------------------------------------------------------------------
284
284
285 class MagicsManager(Configurable):
285 class MagicsManager(Configurable):
286 """Object that handles all magic-related functionality for IPython.
286 """Object that handles all magic-related functionality for IPython.
287 """
287 """
288 # Non-configurable class attributes
288 # Non-configurable class attributes
289
289
290 # A two-level dict, first keyed by magic type, then by magic function, and
290 # A two-level dict, first keyed by magic type, then by magic function, and
291 # holding the actual callable object as value. This is the dict used for
291 # holding the actual callable object as value. This is the dict used for
292 # magic function dispatch
292 # magic function dispatch
293 magics = Dict()
293 magics = Dict()
294
294
295 # A registry of the original objects that we've been given holding magics.
295 # A registry of the original objects that we've been given holding magics.
296 registry = Dict()
296 registry = Dict()
297
297
298 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
298 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
299
299
300 auto_magic = Bool(True, help=
300 auto_magic = Bool(True, help=
301 "Automatically call line magics without requiring explicit % prefix"
301 "Automatically call line magics without requiring explicit % prefix"
302 ).tag(config=True)
302 ).tag(config=True)
303 @observe('auto_magic')
303 @observe('auto_magic')
304 def _auto_magic_changed(self, change):
304 def _auto_magic_changed(self, change):
305 self.shell.automagic = change['new']
305 self.shell.automagic = change['new']
306
306
307 _auto_status = [
307 _auto_status = [
308 'Automagic is OFF, % prefix IS needed for line magics.',
308 'Automagic is OFF, % prefix IS needed for line magics.',
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
310
310
311 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
311 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
312
312
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
314
314
315 super(MagicsManager, self).__init__(shell=shell, config=config,
315 super(MagicsManager, self).__init__(shell=shell, config=config,
316 user_magics=user_magics, **traits)
316 user_magics=user_magics, **traits)
317 self.magics = dict(line={}, cell={})
317 self.magics = dict(line={}, cell={})
318 # Let's add the user_magics to the registry for uniformity, so *all*
318 # Let's add the user_magics to the registry for uniformity, so *all*
319 # registered magic containers can be found there.
319 # registered magic containers can be found there.
320 self.registry[user_magics.__class__.__name__] = user_magics
320 self.registry[user_magics.__class__.__name__] = user_magics
321
321
322 def auto_status(self):
322 def auto_status(self):
323 """Return descriptive string with automagic status."""
323 """Return descriptive string with automagic status."""
324 return self._auto_status[self.auto_magic]
324 return self._auto_status[self.auto_magic]
325
325
326 def lsmagic(self):
326 def lsmagic(self):
327 """Return a dict of currently available magic functions.
327 """Return a dict of currently available magic functions.
328
328
329 The return dict has the keys 'line' and 'cell', corresponding to the
329 The return dict has the keys 'line' and 'cell', corresponding to the
330 two types of magics we support. Each value is a list of names.
330 two types of magics we support. Each value is a list of names.
331 """
331 """
332 return self.magics
332 return self.magics
333
333
334 def lsmagic_docs(self, brief=False, missing=''):
334 def lsmagic_docs(self, brief=False, missing=''):
335 """Return dict of documentation of magic functions.
335 """Return dict of documentation of magic functions.
336
336
337 The return dict has the keys 'line' and 'cell', corresponding to the
337 The return dict has the keys 'line' and 'cell', corresponding to the
338 two types of magics we support. Each value is a dict keyed by magic
338 two types of magics we support. Each value is a dict keyed by magic
339 name whose value is the function docstring. If a docstring is
339 name whose value is the function docstring. If a docstring is
340 unavailable, the value of `missing` is used instead.
340 unavailable, the value of `missing` is used instead.
341
341
342 If brief is True, only the first line of each docstring will be returned.
342 If brief is True, only the first line of each docstring will be returned.
343 """
343 """
344 docs = {}
344 docs = {}
345 for m_type in self.magics:
345 for m_type in self.magics:
346 m_docs = {}
346 m_docs = {}
347 for m_name, m_func in iteritems(self.magics[m_type]):
347 for m_name, m_func in self.magics[m_type].items():
348 if m_func.__doc__:
348 if m_func.__doc__:
349 if brief:
349 if brief:
350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
351 else:
351 else:
352 m_docs[m_name] = m_func.__doc__.rstrip()
352 m_docs[m_name] = m_func.__doc__.rstrip()
353 else:
353 else:
354 m_docs[m_name] = missing
354 m_docs[m_name] = missing
355 docs[m_type] = m_docs
355 docs[m_type] = m_docs
356 return docs
356 return docs
357
357
358 def register(self, *magic_objects):
358 def register(self, *magic_objects):
359 """Register one or more instances of Magics.
359 """Register one or more instances of Magics.
360
360
361 Take one or more classes or instances of classes that subclass the main
361 Take one or more classes or instances of classes that subclass the main
362 `core.Magic` class, and register them with IPython to use the magic
362 `core.Magic` class, and register them with IPython to use the magic
363 functions they provide. The registration process will then ensure that
363 functions they provide. The registration process will then ensure that
364 any methods that have decorated to provide line and/or cell magics will
364 any methods that have decorated to provide line and/or cell magics will
365 be recognized with the `%x`/`%%x` syntax as a line/cell magic
365 be recognized with the `%x`/`%%x` syntax as a line/cell magic
366 respectively.
366 respectively.
367
367
368 If classes are given, they will be instantiated with the default
368 If classes are given, they will be instantiated with the default
369 constructor. If your classes need a custom constructor, you should
369 constructor. If your classes need a custom constructor, you should
370 instanitate them first and pass the instance.
370 instanitate them first and pass the instance.
371
371
372 The provided arguments can be an arbitrary mix of classes and instances.
372 The provided arguments can be an arbitrary mix of classes and instances.
373
373
374 Parameters
374 Parameters
375 ----------
375 ----------
376 magic_objects : one or more classes or instances
376 magic_objects : one or more classes or instances
377 """
377 """
378 # Start by validating them to ensure they have all had their magic
378 # Start by validating them to ensure they have all had their magic
379 # methods registered at the instance level
379 # methods registered at the instance level
380 for m in magic_objects:
380 for m in magic_objects:
381 if not m.registered:
381 if not m.registered:
382 raise ValueError("Class of magics %r was constructed without "
382 raise ValueError("Class of magics %r was constructed without "
383 "the @register_magics class decorator")
383 "the @register_magics class decorator")
384 if isinstance(m, type):
384 if isinstance(m, type):
385 # If we're given an uninstantiated class
385 # If we're given an uninstantiated class
386 m = m(shell=self.shell)
386 m = m(shell=self.shell)
387
387
388 # Now that we have an instance, we can register it and update the
388 # Now that we have an instance, we can register it and update the
389 # table of callables
389 # table of callables
390 self.registry[m.__class__.__name__] = m
390 self.registry[m.__class__.__name__] = m
391 for mtype in magic_kinds:
391 for mtype in magic_kinds:
392 self.magics[mtype].update(m.magics[mtype])
392 self.magics[mtype].update(m.magics[mtype])
393
393
394 def register_function(self, func, magic_kind='line', magic_name=None):
394 def register_function(self, func, magic_kind='line', magic_name=None):
395 """Expose a standalone function as magic function for IPython.
395 """Expose a standalone function as magic function for IPython.
396
396
397 This will create an IPython magic (line, cell or both) from a
397 This will create an IPython magic (line, cell or both) from a
398 standalone function. The functions should have the following
398 standalone function. The functions should have the following
399 signatures:
399 signatures:
400
400
401 * For line magics: `def f(line)`
401 * For line magics: `def f(line)`
402 * For cell magics: `def f(line, cell)`
402 * For cell magics: `def f(line, cell)`
403 * For a function that does both: `def f(line, cell=None)`
403 * For a function that does both: `def f(line, cell=None)`
404
404
405 In the latter case, the function will be called with `cell==None` when
405 In the latter case, the function will be called with `cell==None` when
406 invoked as `%f`, and with cell as a string when invoked as `%%f`.
406 invoked as `%f`, and with cell as a string when invoked as `%%f`.
407
407
408 Parameters
408 Parameters
409 ----------
409 ----------
410 func : callable
410 func : callable
411 Function to be registered as a magic.
411 Function to be registered as a magic.
412
412
413 magic_kind : str
413 magic_kind : str
414 Kind of magic, one of 'line', 'cell' or 'line_cell'
414 Kind of magic, one of 'line', 'cell' or 'line_cell'
415
415
416 magic_name : optional str
416 magic_name : optional str
417 If given, the name the magic will have in the IPython namespace. By
417 If given, the name the magic will have in the IPython namespace. By
418 default, the name of the function itself is used.
418 default, the name of the function itself is used.
419 """
419 """
420
420
421 # Create the new method in the user_magics and register it in the
421 # Create the new method in the user_magics and register it in the
422 # global table
422 # global table
423 validate_type(magic_kind)
423 validate_type(magic_kind)
424 magic_name = func.__name__ if magic_name is None else magic_name
424 magic_name = func.__name__ if magic_name is None else magic_name
425 setattr(self.user_magics, magic_name, func)
425 setattr(self.user_magics, magic_name, func)
426 record_magic(self.magics, magic_kind, magic_name, func)
426 record_magic(self.magics, magic_kind, magic_name, func)
427
427
428 def register_alias(self, alias_name, magic_name, magic_kind='line'):
428 def register_alias(self, alias_name, magic_name, magic_kind='line'):
429 """Register an alias to a magic function.
429 """Register an alias to a magic function.
430
430
431 The alias is an instance of :class:`MagicAlias`, which holds the
431 The alias is an instance of :class:`MagicAlias`, which holds the
432 name and kind of the magic it should call. Binding is done at
432 name and kind of the magic it should call. Binding is done at
433 call time, so if the underlying magic function is changed the alias
433 call time, so if the underlying magic function is changed the alias
434 will call the new function.
434 will call the new function.
435
435
436 Parameters
436 Parameters
437 ----------
437 ----------
438 alias_name : str
438 alias_name : str
439 The name of the magic to be registered.
439 The name of the magic to be registered.
440
440
441 magic_name : str
441 magic_name : str
442 The name of an existing magic.
442 The name of an existing magic.
443
443
444 magic_kind : str
444 magic_kind : str
445 Kind of magic, one of 'line' or 'cell'
445 Kind of magic, one of 'line' or 'cell'
446 """
446 """
447
447
448 # `validate_type` is too permissive, as it allows 'line_cell'
448 # `validate_type` is too permissive, as it allows 'line_cell'
449 # which we do not handle.
449 # which we do not handle.
450 if magic_kind not in magic_kinds:
450 if magic_kind not in magic_kinds:
451 raise ValueError('magic_kind must be one of %s, %s given' %
451 raise ValueError('magic_kind must be one of %s, %s given' %
452 magic_kinds, magic_kind)
452 magic_kinds, magic_kind)
453
453
454 alias = MagicAlias(self.shell, magic_name, magic_kind)
454 alias = MagicAlias(self.shell, magic_name, magic_kind)
455 setattr(self.user_magics, alias_name, alias)
455 setattr(self.user_magics, alias_name, alias)
456 record_magic(self.magics, magic_kind, alias_name, alias)
456 record_magic(self.magics, magic_kind, alias_name, alias)
457
457
458 # Key base class that provides the central functionality for magics.
458 # Key base class that provides the central functionality for magics.
459
459
460
460
461 class Magics(Configurable):
461 class Magics(Configurable):
462 """Base class for implementing magic functions.
462 """Base class for implementing magic functions.
463
463
464 Shell functions which can be reached as %function_name. All magic
464 Shell functions which can be reached as %function_name. All magic
465 functions should accept a string, which they can parse for their own
465 functions should accept a string, which they can parse for their own
466 needs. This can make some functions easier to type, eg `%cd ../`
466 needs. This can make some functions easier to type, eg `%cd ../`
467 vs. `%cd("../")`
467 vs. `%cd("../")`
468
468
469 Classes providing magic functions need to subclass this class, and they
469 Classes providing magic functions need to subclass this class, and they
470 MUST:
470 MUST:
471
471
472 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
472 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
473 individual methods as magic functions, AND
473 individual methods as magic functions, AND
474
474
475 - Use the class decorator `@magics_class` to ensure that the magic
475 - Use the class decorator `@magics_class` to ensure that the magic
476 methods are properly registered at the instance level upon instance
476 methods are properly registered at the instance level upon instance
477 initialization.
477 initialization.
478
478
479 See :mod:`magic_functions` for examples of actual implementation classes.
479 See :mod:`magic_functions` for examples of actual implementation classes.
480 """
480 """
481 # Dict holding all command-line options for each magic.
481 # Dict holding all command-line options for each magic.
482 options_table = None
482 options_table = None
483 # Dict for the mapping of magic names to methods, set by class decorator
483 # Dict for the mapping of magic names to methods, set by class decorator
484 magics = None
484 magics = None
485 # Flag to check that the class decorator was properly applied
485 # Flag to check that the class decorator was properly applied
486 registered = False
486 registered = False
487 # Instance of IPython shell
487 # Instance of IPython shell
488 shell = None
488 shell = None
489
489
490 def __init__(self, shell=None, **kwargs):
490 def __init__(self, shell=None, **kwargs):
491 if not(self.__class__.registered):
491 if not(self.__class__.registered):
492 raise ValueError('Magics subclass without registration - '
492 raise ValueError('Magics subclass without registration - '
493 'did you forget to apply @magics_class?')
493 'did you forget to apply @magics_class?')
494 if shell is not None:
494 if shell is not None:
495 if hasattr(shell, 'configurables'):
495 if hasattr(shell, 'configurables'):
496 shell.configurables.append(self)
496 shell.configurables.append(self)
497 if hasattr(shell, 'config'):
497 if hasattr(shell, 'config'):
498 kwargs.setdefault('parent', shell)
498 kwargs.setdefault('parent', shell)
499
499
500 self.shell = shell
500 self.shell = shell
501 self.options_table = {}
501 self.options_table = {}
502 # The method decorators are run when the instance doesn't exist yet, so
502 # The method decorators are run when the instance doesn't exist yet, so
503 # they can only record the names of the methods they are supposed to
503 # they can only record the names of the methods they are supposed to
504 # grab. Only now, that the instance exists, can we create the proper
504 # grab. Only now, that the instance exists, can we create the proper
505 # mapping to bound methods. So we read the info off the original names
505 # mapping to bound methods. So we read the info off the original names
506 # table and replace each method name by the actual bound method.
506 # table and replace each method name by the actual bound method.
507 # But we mustn't clobber the *class* mapping, in case of multiple instances.
507 # But we mustn't clobber the *class* mapping, in case of multiple instances.
508 class_magics = self.magics
508 class_magics = self.magics
509 self.magics = {}
509 self.magics = {}
510 for mtype in magic_kinds:
510 for mtype in magic_kinds:
511 tab = self.magics[mtype] = {}
511 tab = self.magics[mtype] = {}
512 cls_tab = class_magics[mtype]
512 cls_tab = class_magics[mtype]
513 for magic_name, meth_name in iteritems(cls_tab):
513 for magic_name, meth_name in cls_tab.items():
514 if isinstance(meth_name, string_types):
514 if isinstance(meth_name, string_types):
515 # it's a method name, grab it
515 # it's a method name, grab it
516 tab[magic_name] = getattr(self, meth_name)
516 tab[magic_name] = getattr(self, meth_name)
517 else:
517 else:
518 # it's the real thing
518 # it's the real thing
519 tab[magic_name] = meth_name
519 tab[magic_name] = meth_name
520 # Configurable **needs** to be initiated at the end or the config
520 # Configurable **needs** to be initiated at the end or the config
521 # magics get screwed up.
521 # magics get screwed up.
522 super(Magics, self).__init__(**kwargs)
522 super(Magics, self).__init__(**kwargs)
523
523
524 def arg_err(self,func):
524 def arg_err(self,func):
525 """Print docstring if incorrect arguments were passed"""
525 """Print docstring if incorrect arguments were passed"""
526 print('Error in arguments:')
526 print('Error in arguments:')
527 print(oinspect.getdoc(func))
527 print(oinspect.getdoc(func))
528
528
529 def format_latex(self, strng):
529 def format_latex(self, strng):
530 """Format a string for latex inclusion."""
530 """Format a string for latex inclusion."""
531
531
532 # Characters that need to be escaped for latex:
532 # Characters that need to be escaped for latex:
533 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
533 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
534 # Magic command names as headers:
534 # Magic command names as headers:
535 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
535 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
536 re.MULTILINE)
536 re.MULTILINE)
537 # Magic commands
537 # Magic commands
538 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
538 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
539 re.MULTILINE)
539 re.MULTILINE)
540 # Paragraph continue
540 # Paragraph continue
541 par_re = re.compile(r'\\$',re.MULTILINE)
541 par_re = re.compile(r'\\$',re.MULTILINE)
542
542
543 # The "\n" symbol
543 # The "\n" symbol
544 newline_re = re.compile(r'\\n')
544 newline_re = re.compile(r'\\n')
545
545
546 # Now build the string for output:
546 # Now build the string for output:
547 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
547 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
548 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
548 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
549 strng)
549 strng)
550 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
550 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
551 strng = par_re.sub(r'\\\\',strng)
551 strng = par_re.sub(r'\\\\',strng)
552 strng = escape_re.sub(r'\\\1',strng)
552 strng = escape_re.sub(r'\\\1',strng)
553 strng = newline_re.sub(r'\\textbackslash{}n',strng)
553 strng = newline_re.sub(r'\\textbackslash{}n',strng)
554 return strng
554 return strng
555
555
556 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
556 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
557 """Parse options passed to an argument string.
557 """Parse options passed to an argument string.
558
558
559 The interface is similar to that of :func:`getopt.getopt`, but it
559 The interface is similar to that of :func:`getopt.getopt`, but it
560 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
560 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
561 and the stripped argument string still as a string.
561 and the stripped argument string still as a string.
562
562
563 arg_str is quoted as a true sys.argv vector by using shlex.split.
563 arg_str is quoted as a true sys.argv vector by using shlex.split.
564 This allows us to easily expand variables, glob files, quote
564 This allows us to easily expand variables, glob files, quote
565 arguments, etc.
565 arguments, etc.
566
566
567 Parameters
567 Parameters
568 ----------
568 ----------
569
569
570 arg_str : str
570 arg_str : str
571 The arguments to parse.
571 The arguments to parse.
572
572
573 opt_str : str
573 opt_str : str
574 The options specification.
574 The options specification.
575
575
576 mode : str, default 'string'
576 mode : str, default 'string'
577 If given as 'list', the argument string is returned as a list (split
577 If given as 'list', the argument string is returned as a list (split
578 on whitespace) instead of a string.
578 on whitespace) instead of a string.
579
579
580 list_all : bool, default False
580 list_all : bool, default False
581 Put all option values in lists. Normally only options
581 Put all option values in lists. Normally only options
582 appearing more than once are put in a list.
582 appearing more than once are put in a list.
583
583
584 posix : bool, default True
584 posix : bool, default True
585 Whether to split the input line in POSIX mode or not, as per the
585 Whether to split the input line in POSIX mode or not, as per the
586 conventions outlined in the :mod:`shlex` module from the standard
586 conventions outlined in the :mod:`shlex` module from the standard
587 library.
587 library.
588 """
588 """
589
589
590 # inject default options at the beginning of the input line
590 # inject default options at the beginning of the input line
591 caller = sys._getframe(1).f_code.co_name
591 caller = sys._getframe(1).f_code.co_name
592 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
592 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
593
593
594 mode = kw.get('mode','string')
594 mode = kw.get('mode','string')
595 if mode not in ['string','list']:
595 if mode not in ['string','list']:
596 raise ValueError('incorrect mode given: %s' % mode)
596 raise ValueError('incorrect mode given: %s' % mode)
597 # Get options
597 # Get options
598 list_all = kw.get('list_all',0)
598 list_all = kw.get('list_all',0)
599 posix = kw.get('posix', os.name == 'posix')
599 posix = kw.get('posix', os.name == 'posix')
600 strict = kw.get('strict', True)
600 strict = kw.get('strict', True)
601
601
602 # Check if we have more than one argument to warrant extra processing:
602 # Check if we have more than one argument to warrant extra processing:
603 odict = {} # Dictionary with options
603 odict = {} # Dictionary with options
604 args = arg_str.split()
604 args = arg_str.split()
605 if len(args) >= 1:
605 if len(args) >= 1:
606 # If the list of inputs only has 0 or 1 thing in it, there's no
606 # If the list of inputs only has 0 or 1 thing in it, there's no
607 # need to look for options
607 # need to look for options
608 argv = arg_split(arg_str, posix, strict)
608 argv = arg_split(arg_str, posix, strict)
609 # Do regular option processing
609 # Do regular option processing
610 try:
610 try:
611 opts,args = getopt(argv, opt_str, long_opts)
611 opts,args = getopt(argv, opt_str, long_opts)
612 except GetoptError as e:
612 except GetoptError as e:
613 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
613 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
614 " ".join(long_opts)))
614 " ".join(long_opts)))
615 for o,a in opts:
615 for o,a in opts:
616 if o.startswith('--'):
616 if o.startswith('--'):
617 o = o[2:]
617 o = o[2:]
618 else:
618 else:
619 o = o[1:]
619 o = o[1:]
620 try:
620 try:
621 odict[o].append(a)
621 odict[o].append(a)
622 except AttributeError:
622 except AttributeError:
623 odict[o] = [odict[o],a]
623 odict[o] = [odict[o],a]
624 except KeyError:
624 except KeyError:
625 if list_all:
625 if list_all:
626 odict[o] = [a]
626 odict[o] = [a]
627 else:
627 else:
628 odict[o] = a
628 odict[o] = a
629
629
630 # Prepare opts,args for return
630 # Prepare opts,args for return
631 opts = Struct(odict)
631 opts = Struct(odict)
632 if mode == 'string':
632 if mode == 'string':
633 args = ' '.join(args)
633 args = ' '.join(args)
634
634
635 return opts,args
635 return opts,args
636
636
637 def default_option(self, fn, optstr):
637 def default_option(self, fn, optstr):
638 """Make an entry in the options_table for fn, with value optstr"""
638 """Make an entry in the options_table for fn, with value optstr"""
639
639
640 if fn not in self.lsmagic():
640 if fn not in self.lsmagic():
641 error("%s is not a magic function" % fn)
641 error("%s is not a magic function" % fn)
642 self.options_table[fn] = optstr
642 self.options_table[fn] = optstr
643
643
644
644
645 class MagicAlias(object):
645 class MagicAlias(object):
646 """An alias to another magic function.
646 """An alias to another magic function.
647
647
648 An alias is determined by its magic name and magic kind. Lookup
648 An alias is determined by its magic name and magic kind. Lookup
649 is done at call time, so if the underlying magic changes the alias
649 is done at call time, so if the underlying magic changes the alias
650 will call the new function.
650 will call the new function.
651
651
652 Use the :meth:`MagicsManager.register_alias` method or the
652 Use the :meth:`MagicsManager.register_alias` method or the
653 `%alias_magic` magic function to create and register a new alias.
653 `%alias_magic` magic function to create and register a new alias.
654 """
654 """
655 def __init__(self, shell, magic_name, magic_kind):
655 def __init__(self, shell, magic_name, magic_kind):
656 self.shell = shell
656 self.shell = shell
657 self.magic_name = magic_name
657 self.magic_name = magic_name
658 self.magic_kind = magic_kind
658 self.magic_kind = magic_kind
659
659
660 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
660 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
661 self.__doc__ = "Alias for `%s`." % self.pretty_target
661 self.__doc__ = "Alias for `%s`." % self.pretty_target
662
662
663 self._in_call = False
663 self._in_call = False
664
664
665 def __call__(self, *args, **kwargs):
665 def __call__(self, *args, **kwargs):
666 """Call the magic alias."""
666 """Call the magic alias."""
667 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
667 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
668 if fn is None:
668 if fn is None:
669 raise UsageError("Magic `%s` not found." % self.pretty_target)
669 raise UsageError("Magic `%s` not found." % self.pretty_target)
670
670
671 # Protect against infinite recursion.
671 # Protect against infinite recursion.
672 if self._in_call:
672 if self._in_call:
673 raise UsageError("Infinite recursion detected; "
673 raise UsageError("Infinite recursion detected; "
674 "magic aliases cannot call themselves.")
674 "magic aliases cannot call themselves.")
675 self._in_call = True
675 self._in_call = True
676 try:
676 try:
677 return fn(*args, **kwargs)
677 return fn(*args, **kwargs)
678 finally:
678 finally:
679 self._in_call = False
679 self._in_call = False
@@ -1,1373 +1,1372 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 import ast
8 import ast
9 import bdb
9 import bdb
10 import gc
10 import gc
11 import itertools
11 import itertools
12 import os
12 import os
13 import sys
13 import sys
14 import time
14 import time
15 import timeit
15 import timeit
16 import math
16 import math
17 from pdb import Restart
17 from pdb import Restart
18
18
19 # cProfile was added in Python2.5
19 # cProfile was added in Python2.5
20 try:
20 try:
21 import cProfile as profile
21 import cProfile as profile
22 import pstats
22 import pstats
23 except ImportError:
23 except ImportError:
24 # profile isn't bundled by default in Debian for license reasons
24 # profile isn't bundled by default in Debian for license reasons
25 try:
25 try:
26 import profile, pstats
26 import profile, pstats
27 except ImportError:
27 except ImportError:
28 profile = pstats = None
28 profile = pstats = None
29
29
30 from IPython.core import oinspect
30 from IPython.core import oinspect
31 from IPython.core import magic_arguments
31 from IPython.core import magic_arguments
32 from IPython.core import page
32 from IPython.core import page
33 from IPython.core.error import UsageError
33 from IPython.core.error import UsageError
34 from IPython.core.macro import Macro
34 from IPython.core.macro import Macro
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 line_cell_magic, on_off, needs_local_scope)
36 line_cell_magic, on_off, needs_local_scope)
37 from IPython.testing.skipdoctest import skip_doctest
37 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.utils import py3compat
38 from IPython.utils import py3compat
39 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
39 from IPython.utils.py3compat import builtin_mod, PY3
40 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.capture import capture_output
41 from IPython.utils.capture import capture_output
42 from IPython.utils.ipstruct import Struct
42 from IPython.utils.ipstruct import Struct
43 from IPython.utils.module_paths import find_mod
43 from IPython.utils.module_paths import find_mod
44 from IPython.utils.path import get_py_filename, shellglob
44 from IPython.utils.path import get_py_filename, shellglob
45 from IPython.utils.timing import clock, clock2
45 from IPython.utils.timing import clock, clock2
46 from warnings import warn
46 from warnings import warn
47 from logging import error
47 from logging import error
48
48
49 if PY3:
49 if PY3:
50 from io import StringIO
50 from io import StringIO
51 else:
51 else:
52 from StringIO import StringIO
52 from StringIO import StringIO
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Magic implementation classes
55 # Magic implementation classes
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58
58
59 class TimeitResult(object):
59 class TimeitResult(object):
60 """
60 """
61 Object returned by the timeit magic with info about the run.
61 Object returned by the timeit magic with info about the run.
62
62
63 Contains the following attributes :
63 Contains the following attributes :
64
64
65 loops: (int) number of loops done per measurement
65 loops: (int) number of loops done per measurement
66 repeat: (int) number of times the measurement has been repeated
66 repeat: (int) number of times the measurement has been repeated
67 best: (float) best execution time / number
67 best: (float) best execution time / number
68 all_runs: (list of float) execution time of each run (in s)
68 all_runs: (list of float) execution time of each run (in s)
69 compile_time: (float) time of statement compilation (s)
69 compile_time: (float) time of statement compilation (s)
70
70
71 """
71 """
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
72 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
73 self.loops = loops
73 self.loops = loops
74 self.repeat = repeat
74 self.repeat = repeat
75 self.best = best
75 self.best = best
76 self.worst = worst
76 self.worst = worst
77 self.all_runs = all_runs
77 self.all_runs = all_runs
78 self.compile_time = compile_time
78 self.compile_time = compile_time
79 self._precision = precision
79 self._precision = precision
80 self.timings = [ dt / self.loops for dt in all_runs]
80 self.timings = [ dt / self.loops for dt in all_runs]
81
81
82 @property
82 @property
83 def average(self):
83 def average(self):
84 return math.fsum(self.timings) / len(self.timings)
84 return math.fsum(self.timings) / len(self.timings)
85
85
86 @property
86 @property
87 def stdev(self):
87 def stdev(self):
88 mean = self.average
88 mean = self.average
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
89 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
90
90
91 def __str__(self):
91 def __str__(self):
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
92 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
93 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
94 _format_time(self.average, self._precision),
94 _format_time(self.average, self._precision),
95 _format_time(self.stdev, self._precision)))
95 _format_time(self.stdev, self._precision)))
96
96
97 def _repr_pretty_(self, p , cycle):
97 def _repr_pretty_(self, p , cycle):
98 unic = self.__str__()
98 unic = self.__str__()
99 p.text(u'<TimeitResult : '+unic+u'>')
99 p.text(u'<TimeitResult : '+unic+u'>')
100
100
101
101
102
102
103 class TimeitTemplateFiller(ast.NodeTransformer):
103 class TimeitTemplateFiller(ast.NodeTransformer):
104 """Fill in the AST template for timing execution.
104 """Fill in the AST template for timing execution.
105
105
106 This is quite closely tied to the template definition, which is in
106 This is quite closely tied to the template definition, which is in
107 :meth:`ExecutionMagics.timeit`.
107 :meth:`ExecutionMagics.timeit`.
108 """
108 """
109 def __init__(self, ast_setup, ast_stmt):
109 def __init__(self, ast_setup, ast_stmt):
110 self.ast_setup = ast_setup
110 self.ast_setup = ast_setup
111 self.ast_stmt = ast_stmt
111 self.ast_stmt = ast_stmt
112
112
113 def visit_FunctionDef(self, node):
113 def visit_FunctionDef(self, node):
114 "Fill in the setup statement"
114 "Fill in the setup statement"
115 self.generic_visit(node)
115 self.generic_visit(node)
116 if node.name == "inner":
116 if node.name == "inner":
117 node.body[:1] = self.ast_setup.body
117 node.body[:1] = self.ast_setup.body
118
118
119 return node
119 return node
120
120
121 def visit_For(self, node):
121 def visit_For(self, node):
122 "Fill in the statement to be timed"
122 "Fill in the statement to be timed"
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
123 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
124 node.body = self.ast_stmt.body
124 node.body = self.ast_stmt.body
125 return node
125 return node
126
126
127
127
128 class Timer(timeit.Timer):
128 class Timer(timeit.Timer):
129 """Timer class that explicitly uses self.inner
129 """Timer class that explicitly uses self.inner
130
130
131 which is an undocumented implementation detail of CPython,
131 which is an undocumented implementation detail of CPython,
132 not shared by PyPy.
132 not shared by PyPy.
133 """
133 """
134 # Timer.timeit copied from CPython 3.4.2
134 # Timer.timeit copied from CPython 3.4.2
135 def timeit(self, number=timeit.default_number):
135 def timeit(self, number=timeit.default_number):
136 """Time 'number' executions of the main statement.
136 """Time 'number' executions of the main statement.
137
137
138 To be precise, this executes the setup statement once, and
138 To be precise, this executes the setup statement once, and
139 then returns the time it takes to execute the main statement
139 then returns the time it takes to execute the main statement
140 a number of times, as a float measured in seconds. The
140 a number of times, as a float measured in seconds. The
141 argument is the number of times through the loop, defaulting
141 argument is the number of times through the loop, defaulting
142 to one million. The main statement, the setup statement and
142 to one million. The main statement, the setup statement and
143 the timer function to be used are passed to the constructor.
143 the timer function to be used are passed to the constructor.
144 """
144 """
145 it = itertools.repeat(None, number)
145 it = itertools.repeat(None, number)
146 gcold = gc.isenabled()
146 gcold = gc.isenabled()
147 gc.disable()
147 gc.disable()
148 try:
148 try:
149 timing = self.inner(it, self.timer)
149 timing = self.inner(it, self.timer)
150 finally:
150 finally:
151 if gcold:
151 if gcold:
152 gc.enable()
152 gc.enable()
153 return timing
153 return timing
154
154
155
155
156 @magics_class
156 @magics_class
157 class ExecutionMagics(Magics):
157 class ExecutionMagics(Magics):
158 """Magics related to code execution, debugging, profiling, etc.
158 """Magics related to code execution, debugging, profiling, etc.
159
159
160 """
160 """
161
161
162 def __init__(self, shell):
162 def __init__(self, shell):
163 super(ExecutionMagics, self).__init__(shell)
163 super(ExecutionMagics, self).__init__(shell)
164 if profile is None:
164 if profile is None:
165 self.prun = self.profile_missing_notice
165 self.prun = self.profile_missing_notice
166 # Default execution function used to actually run user code.
166 # Default execution function used to actually run user code.
167 self.default_runner = None
167 self.default_runner = None
168
168
169 def profile_missing_notice(self, *args, **kwargs):
169 def profile_missing_notice(self, *args, **kwargs):
170 error("""\
170 error("""\
171 The profile module could not be found. It has been removed from the standard
171 The profile module could not be found. It has been removed from the standard
172 python packages because of its non-free license. To use profiling, install the
172 python packages because of its non-free license. To use profiling, install the
173 python-profiler package from non-free.""")
173 python-profiler package from non-free.""")
174
174
175 @skip_doctest
175 @skip_doctest
176 @line_cell_magic
176 @line_cell_magic
177 def prun(self, parameter_s='', cell=None):
177 def prun(self, parameter_s='', cell=None):
178
178
179 """Run a statement through the python code profiler.
179 """Run a statement through the python code profiler.
180
180
181 Usage, in line mode:
181 Usage, in line mode:
182 %prun [options] statement
182 %prun [options] statement
183
183
184 Usage, in cell mode:
184 Usage, in cell mode:
185 %%prun [options] [statement]
185 %%prun [options] [statement]
186 code...
186 code...
187 code...
187 code...
188
188
189 In cell mode, the additional code lines are appended to the (possibly
189 In cell mode, the additional code lines are appended to the (possibly
190 empty) statement in the first line. Cell mode allows you to easily
190 empty) statement in the first line. Cell mode allows you to easily
191 profile multiline blocks without having to put them in a separate
191 profile multiline blocks without having to put them in a separate
192 function.
192 function.
193
193
194 The given statement (which doesn't require quote marks) is run via the
194 The given statement (which doesn't require quote marks) is run via the
195 python profiler in a manner similar to the profile.run() function.
195 python profiler in a manner similar to the profile.run() function.
196 Namespaces are internally managed to work correctly; profile.run
196 Namespaces are internally managed to work correctly; profile.run
197 cannot be used in IPython because it makes certain assumptions about
197 cannot be used in IPython because it makes certain assumptions about
198 namespaces which do not hold under IPython.
198 namespaces which do not hold under IPython.
199
199
200 Options:
200 Options:
201
201
202 -l <limit>
202 -l <limit>
203 you can place restrictions on what or how much of the
203 you can place restrictions on what or how much of the
204 profile gets printed. The limit value can be:
204 profile gets printed. The limit value can be:
205
205
206 * A string: only information for function names containing this string
206 * A string: only information for function names containing this string
207 is printed.
207 is printed.
208
208
209 * An integer: only these many lines are printed.
209 * An integer: only these many lines are printed.
210
210
211 * A float (between 0 and 1): this fraction of the report is printed
211 * A float (between 0 and 1): this fraction of the report is printed
212 (for example, use a limit of 0.4 to see the topmost 40% only).
212 (for example, use a limit of 0.4 to see the topmost 40% only).
213
213
214 You can combine several limits with repeated use of the option. For
214 You can combine several limits with repeated use of the option. For
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
216 information about class constructors.
216 information about class constructors.
217
217
218 -r
218 -r
219 return the pstats.Stats object generated by the profiling. This
219 return the pstats.Stats object generated by the profiling. This
220 object has all the information about the profile in it, and you can
220 object has all the information about the profile in it, and you can
221 later use it for further analysis or in other functions.
221 later use it for further analysis or in other functions.
222
222
223 -s <key>
223 -s <key>
224 sort profile by given key. You can provide more than one key
224 sort profile by given key. You can provide more than one key
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
225 by using the option several times: '-s key1 -s key2 -s key3...'. The
226 default sorting key is 'time'.
226 default sorting key is 'time'.
227
227
228 The following is copied verbatim from the profile documentation
228 The following is copied verbatim from the profile documentation
229 referenced below:
229 referenced below:
230
230
231 When more than one key is provided, additional keys are used as
231 When more than one key is provided, additional keys are used as
232 secondary criteria when the there is equality in all keys selected
232 secondary criteria when the there is equality in all keys selected
233 before them.
233 before them.
234
234
235 Abbreviations can be used for any key names, as long as the
235 Abbreviations can be used for any key names, as long as the
236 abbreviation is unambiguous. The following are the keys currently
236 abbreviation is unambiguous. The following are the keys currently
237 defined:
237 defined:
238
238
239 ============ =====================
239 ============ =====================
240 Valid Arg Meaning
240 Valid Arg Meaning
241 ============ =====================
241 ============ =====================
242 "calls" call count
242 "calls" call count
243 "cumulative" cumulative time
243 "cumulative" cumulative time
244 "file" file name
244 "file" file name
245 "module" file name
245 "module" file name
246 "pcalls" primitive call count
246 "pcalls" primitive call count
247 "line" line number
247 "line" line number
248 "name" function name
248 "name" function name
249 "nfl" name/file/line
249 "nfl" name/file/line
250 "stdname" standard name
250 "stdname" standard name
251 "time" internal time
251 "time" internal time
252 ============ =====================
252 ============ =====================
253
253
254 Note that all sorts on statistics are in descending order (placing
254 Note that all sorts on statistics are in descending order (placing
255 most time consuming items first), where as name, file, and line number
255 most time consuming items first), where as name, file, and line number
256 searches are in ascending order (i.e., alphabetical). The subtle
256 searches are in ascending order (i.e., alphabetical). The subtle
257 distinction between "nfl" and "stdname" is that the standard name is a
257 distinction between "nfl" and "stdname" is that the standard name is a
258 sort of the name as printed, which means that the embedded line
258 sort of the name as printed, which means that the embedded line
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
259 numbers get compared in an odd way. For example, lines 3, 20, and 40
260 would (if the file names were the same) appear in the string order
260 would (if the file names were the same) appear in the string order
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
262 line numbers. In fact, sort_stats("nfl") is the same as
262 line numbers. In fact, sort_stats("nfl") is the same as
263 sort_stats("name", "file", "line").
263 sort_stats("name", "file", "line").
264
264
265 -T <filename>
265 -T <filename>
266 save profile results as shown on screen to a text
266 save profile results as shown on screen to a text
267 file. The profile is still shown on screen.
267 file. The profile is still shown on screen.
268
268
269 -D <filename>
269 -D <filename>
270 save (via dump_stats) profile statistics to given
270 save (via dump_stats) profile statistics to given
271 filename. This data is in a format understood by the pstats module, and
271 filename. This data is in a format understood by the pstats module, and
272 is generated by a call to the dump_stats() method of profile
272 is generated by a call to the dump_stats() method of profile
273 objects. The profile is still shown on screen.
273 objects. The profile is still shown on screen.
274
274
275 -q
275 -q
276 suppress output to the pager. Best used with -T and/or -D above.
276 suppress output to the pager. Best used with -T and/or -D above.
277
277
278 If you want to run complete programs under the profiler's control, use
278 If you want to run complete programs under the profiler's control, use
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
280 contains profiler specific options as described here.
280 contains profiler specific options as described here.
281
281
282 You can read the complete documentation for the profile module with::
282 You can read the complete documentation for the profile module with::
283
283
284 In [1]: import profile; profile.help()
284 In [1]: import profile; profile.help()
285 """
285 """
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
286 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
287 list_all=True, posix=False)
287 list_all=True, posix=False)
288 if cell is not None:
288 if cell is not None:
289 arg_str += '\n' + cell
289 arg_str += '\n' + cell
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
290 arg_str = self.shell.input_splitter.transform_cell(arg_str)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
291 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
292
292
293 def _run_with_profiler(self, code, opts, namespace):
293 def _run_with_profiler(self, code, opts, namespace):
294 """
294 """
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
295 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
296
296
297 Parameters
297 Parameters
298 ----------
298 ----------
299 code : str
299 code : str
300 Code to be executed.
300 Code to be executed.
301 opts : Struct
301 opts : Struct
302 Options parsed by `self.parse_options`.
302 Options parsed by `self.parse_options`.
303 namespace : dict
303 namespace : dict
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
304 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
305
305
306 """
306 """
307
307
308 # Fill default values for unspecified options:
308 # Fill default values for unspecified options:
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
309 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
310
310
311 prof = profile.Profile()
311 prof = profile.Profile()
312 try:
312 try:
313 prof = prof.runctx(code, namespace, namespace)
313 prof = prof.runctx(code, namespace, namespace)
314 sys_exit = ''
314 sys_exit = ''
315 except SystemExit:
315 except SystemExit:
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
316 sys_exit = """*** SystemExit exception caught in code being profiled."""
317
317
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
318 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
319
319
320 lims = opts.l
320 lims = opts.l
321 if lims:
321 if lims:
322 lims = [] # rebuild lims with ints/floats/strings
322 lims = [] # rebuild lims with ints/floats/strings
323 for lim in opts.l:
323 for lim in opts.l:
324 try:
324 try:
325 lims.append(int(lim))
325 lims.append(int(lim))
326 except ValueError:
326 except ValueError:
327 try:
327 try:
328 lims.append(float(lim))
328 lims.append(float(lim))
329 except ValueError:
329 except ValueError:
330 lims.append(lim)
330 lims.append(lim)
331
331
332 # Trap output.
332 # Trap output.
333 stdout_trap = StringIO()
333 stdout_trap = StringIO()
334 stats_stream = stats.stream
334 stats_stream = stats.stream
335 try:
335 try:
336 stats.stream = stdout_trap
336 stats.stream = stdout_trap
337 stats.print_stats(*lims)
337 stats.print_stats(*lims)
338 finally:
338 finally:
339 stats.stream = stats_stream
339 stats.stream = stats_stream
340
340
341 output = stdout_trap.getvalue()
341 output = stdout_trap.getvalue()
342 output = output.rstrip()
342 output = output.rstrip()
343
343
344 if 'q' not in opts:
344 if 'q' not in opts:
345 page.page(output)
345 page.page(output)
346 print(sys_exit, end=' ')
346 print(sys_exit, end=' ')
347
347
348 dump_file = opts.D[0]
348 dump_file = opts.D[0]
349 text_file = opts.T[0]
349 text_file = opts.T[0]
350 if dump_file:
350 if dump_file:
351 prof.dump_stats(dump_file)
351 prof.dump_stats(dump_file)
352 print('\n*** Profile stats marshalled to file',\
352 print('\n*** Profile stats marshalled to file',\
353 repr(dump_file)+'.',sys_exit)
353 repr(dump_file)+'.',sys_exit)
354 if text_file:
354 if text_file:
355 pfile = open(text_file,'w')
355 pfile = open(text_file,'w')
356 pfile.write(output)
356 pfile.write(output)
357 pfile.close()
357 pfile.close()
358 print('\n*** Profile printout saved to text file',\
358 print('\n*** Profile printout saved to text file',\
359 repr(text_file)+'.',sys_exit)
359 repr(text_file)+'.',sys_exit)
360
360
361 if 'r' in opts:
361 if 'r' in opts:
362 return stats
362 return stats
363 else:
363 else:
364 return None
364 return None
365
365
366 @line_magic
366 @line_magic
367 def pdb(self, parameter_s=''):
367 def pdb(self, parameter_s=''):
368 """Control the automatic calling of the pdb interactive debugger.
368 """Control the automatic calling of the pdb interactive debugger.
369
369
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
370 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
371 argument it works as a toggle.
371 argument it works as a toggle.
372
372
373 When an exception is triggered, IPython can optionally call the
373 When an exception is triggered, IPython can optionally call the
374 interactive pdb debugger after the traceback printout. %pdb toggles
374 interactive pdb debugger after the traceback printout. %pdb toggles
375 this feature on and off.
375 this feature on and off.
376
376
377 The initial state of this feature is set in your configuration
377 The initial state of this feature is set in your configuration
378 file (the option is ``InteractiveShell.pdb``).
378 file (the option is ``InteractiveShell.pdb``).
379
379
380 If you want to just activate the debugger AFTER an exception has fired,
380 If you want to just activate the debugger AFTER an exception has fired,
381 without having to type '%pdb on' and rerunning your code, you can use
381 without having to type '%pdb on' and rerunning your code, you can use
382 the %debug magic."""
382 the %debug magic."""
383
383
384 par = parameter_s.strip().lower()
384 par = parameter_s.strip().lower()
385
385
386 if par:
386 if par:
387 try:
387 try:
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
388 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
389 except KeyError:
389 except KeyError:
390 print ('Incorrect argument. Use on/1, off/0, '
390 print ('Incorrect argument. Use on/1, off/0, '
391 'or nothing for a toggle.')
391 'or nothing for a toggle.')
392 return
392 return
393 else:
393 else:
394 # toggle
394 # toggle
395 new_pdb = not self.shell.call_pdb
395 new_pdb = not self.shell.call_pdb
396
396
397 # set on the shell
397 # set on the shell
398 self.shell.call_pdb = new_pdb
398 self.shell.call_pdb = new_pdb
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
399 print('Automatic pdb calling has been turned',on_off(new_pdb))
400
400
401 @skip_doctest
401 @skip_doctest
402 @magic_arguments.magic_arguments()
402 @magic_arguments.magic_arguments()
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
403 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
404 help="""
404 help="""
405 Set break point at LINE in FILE.
405 Set break point at LINE in FILE.
406 """
406 """
407 )
407 )
408 @magic_arguments.argument('statement', nargs='*',
408 @magic_arguments.argument('statement', nargs='*',
409 help="""
409 help="""
410 Code to run in debugger.
410 Code to run in debugger.
411 You can omit this in cell magic mode.
411 You can omit this in cell magic mode.
412 """
412 """
413 )
413 )
414 @line_cell_magic
414 @line_cell_magic
415 def debug(self, line='', cell=None):
415 def debug(self, line='', cell=None):
416 """Activate the interactive debugger.
416 """Activate the interactive debugger.
417
417
418 This magic command support two ways of activating debugger.
418 This magic command support two ways of activating debugger.
419 One is to activate debugger before executing code. This way, you
419 One is to activate debugger before executing code. This way, you
420 can set a break point, to step through the code from the point.
420 can set a break point, to step through the code from the point.
421 You can use this mode by giving statements to execute and optionally
421 You can use this mode by giving statements to execute and optionally
422 a breakpoint.
422 a breakpoint.
423
423
424 The other one is to activate debugger in post-mortem mode. You can
424 The other one is to activate debugger in post-mortem mode. You can
425 activate this mode simply running %debug without any argument.
425 activate this mode simply running %debug without any argument.
426 If an exception has just occurred, this lets you inspect its stack
426 If an exception has just occurred, this lets you inspect its stack
427 frames interactively. Note that this will always work only on the last
427 frames interactively. Note that this will always work only on the last
428 traceback that occurred, so you must call this quickly after an
428 traceback that occurred, so you must call this quickly after an
429 exception that you wish to inspect has fired, because if another one
429 exception that you wish to inspect has fired, because if another one
430 occurs, it clobbers the previous one.
430 occurs, it clobbers the previous one.
431
431
432 If you want IPython to automatically do this on every exception, see
432 If you want IPython to automatically do this on every exception, see
433 the %pdb magic for more details.
433 the %pdb magic for more details.
434 """
434 """
435 args = magic_arguments.parse_argstring(self.debug, line)
435 args = magic_arguments.parse_argstring(self.debug, line)
436
436
437 if not (args.breakpoint or args.statement or cell):
437 if not (args.breakpoint or args.statement or cell):
438 self._debug_post_mortem()
438 self._debug_post_mortem()
439 else:
439 else:
440 code = "\n".join(args.statement)
440 code = "\n".join(args.statement)
441 if cell:
441 if cell:
442 code += "\n" + cell
442 code += "\n" + cell
443 self._debug_exec(code, args.breakpoint)
443 self._debug_exec(code, args.breakpoint)
444
444
445 def _debug_post_mortem(self):
445 def _debug_post_mortem(self):
446 self.shell.debugger(force=True)
446 self.shell.debugger(force=True)
447
447
448 def _debug_exec(self, code, breakpoint):
448 def _debug_exec(self, code, breakpoint):
449 if breakpoint:
449 if breakpoint:
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
450 (filename, bp_line) = breakpoint.rsplit(':', 1)
451 bp_line = int(bp_line)
451 bp_line = int(bp_line)
452 else:
452 else:
453 (filename, bp_line) = (None, None)
453 (filename, bp_line) = (None, None)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
454 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
455
455
456 @line_magic
456 @line_magic
457 def tb(self, s):
457 def tb(self, s):
458 """Print the last traceback with the currently active exception mode.
458 """Print the last traceback with the currently active exception mode.
459
459
460 See %xmode for changing exception reporting modes."""
460 See %xmode for changing exception reporting modes."""
461 self.shell.showtraceback()
461 self.shell.showtraceback()
462
462
463 @skip_doctest
463 @skip_doctest
464 @line_magic
464 @line_magic
465 def run(self, parameter_s='', runner=None,
465 def run(self, parameter_s='', runner=None,
466 file_finder=get_py_filename):
466 file_finder=get_py_filename):
467 """Run the named file inside IPython as a program.
467 """Run the named file inside IPython as a program.
468
468
469 Usage::
469 Usage::
470
470
471 %run [-n -i -e -G]
471 %run [-n -i -e -G]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
472 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
473 ( -m mod | file ) [args]
473 ( -m mod | file ) [args]
474
474
475 Parameters after the filename are passed as command-line arguments to
475 Parameters after the filename are passed as command-line arguments to
476 the program (put in sys.argv). Then, control returns to IPython's
476 the program (put in sys.argv). Then, control returns to IPython's
477 prompt.
477 prompt.
478
478
479 This is similar to running at a system prompt ``python file args``,
479 This is similar to running at a system prompt ``python file args``,
480 but with the advantage of giving you IPython's tracebacks, and of
480 but with the advantage of giving you IPython's tracebacks, and of
481 loading all variables into your interactive namespace for further use
481 loading all variables into your interactive namespace for further use
482 (unless -p is used, see below).
482 (unless -p is used, see below).
483
483
484 The file is executed in a namespace initially consisting only of
484 The file is executed in a namespace initially consisting only of
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
485 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
486 sees its environment as if it were being run as a stand-alone program
486 sees its environment as if it were being run as a stand-alone program
487 (except for sharing global objects such as previously imported
487 (except for sharing global objects such as previously imported
488 modules). But after execution, the IPython interactive namespace gets
488 modules). But after execution, the IPython interactive namespace gets
489 updated with all variables defined in the program (except for __name__
489 updated with all variables defined in the program (except for __name__
490 and sys.argv). This allows for very convenient loading of code for
490 and sys.argv). This allows for very convenient loading of code for
491 interactive work, while giving each program a 'clean sheet' to run in.
491 interactive work, while giving each program a 'clean sheet' to run in.
492
492
493 Arguments are expanded using shell-like glob match. Patterns
493 Arguments are expanded using shell-like glob match. Patterns
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
494 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
495 tilde '~' will be expanded into user's home directory. Unlike
495 tilde '~' will be expanded into user's home directory. Unlike
496 real shells, quotation does not suppress expansions. Use
496 real shells, quotation does not suppress expansions. Use
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
497 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
498 To completely disable these expansions, you can use -G flag.
498 To completely disable these expansions, you can use -G flag.
499
499
500 Options:
500 Options:
501
501
502 -n
502 -n
503 __name__ is NOT set to '__main__', but to the running file's name
503 __name__ is NOT set to '__main__', but to the running file's name
504 without extension (as python does under import). This allows running
504 without extension (as python does under import). This allows running
505 scripts and reloading the definitions in them without calling code
505 scripts and reloading the definitions in them without calling code
506 protected by an ``if __name__ == "__main__"`` clause.
506 protected by an ``if __name__ == "__main__"`` clause.
507
507
508 -i
508 -i
509 run the file in IPython's namespace instead of an empty one. This
509 run the file in IPython's namespace instead of an empty one. This
510 is useful if you are experimenting with code written in a text editor
510 is useful if you are experimenting with code written in a text editor
511 which depends on variables defined interactively.
511 which depends on variables defined interactively.
512
512
513 -e
513 -e
514 ignore sys.exit() calls or SystemExit exceptions in the script
514 ignore sys.exit() calls or SystemExit exceptions in the script
515 being run. This is particularly useful if IPython is being used to
515 being run. This is particularly useful if IPython is being used to
516 run unittests, which always exit with a sys.exit() call. In such
516 run unittests, which always exit with a sys.exit() call. In such
517 cases you are interested in the output of the test results, not in
517 cases you are interested in the output of the test results, not in
518 seeing a traceback of the unittest module.
518 seeing a traceback of the unittest module.
519
519
520 -t
520 -t
521 print timing information at the end of the run. IPython will give
521 print timing information at the end of the run. IPython will give
522 you an estimated CPU time consumption for your script, which under
522 you an estimated CPU time consumption for your script, which under
523 Unix uses the resource module to avoid the wraparound problems of
523 Unix uses the resource module to avoid the wraparound problems of
524 time.clock(). Under Unix, an estimate of time spent on system tasks
524 time.clock(). Under Unix, an estimate of time spent on system tasks
525 is also given (for Windows platforms this is reported as 0.0).
525 is also given (for Windows platforms this is reported as 0.0).
526
526
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
527 If -t is given, an additional ``-N<N>`` option can be given, where <N>
528 must be an integer indicating how many times you want the script to
528 must be an integer indicating how many times you want the script to
529 run. The final timing report will include total and per run results.
529 run. The final timing report will include total and per run results.
530
530
531 For example (testing the script uniq_stable.py)::
531 For example (testing the script uniq_stable.py)::
532
532
533 In [1]: run -t uniq_stable
533 In [1]: run -t uniq_stable
534
534
535 IPython CPU timings (estimated):
535 IPython CPU timings (estimated):
536 User : 0.19597 s.
536 User : 0.19597 s.
537 System: 0.0 s.
537 System: 0.0 s.
538
538
539 In [2]: run -t -N5 uniq_stable
539 In [2]: run -t -N5 uniq_stable
540
540
541 IPython CPU timings (estimated):
541 IPython CPU timings (estimated):
542 Total runs performed: 5
542 Total runs performed: 5
543 Times : Total Per run
543 Times : Total Per run
544 User : 0.910862 s, 0.1821724 s.
544 User : 0.910862 s, 0.1821724 s.
545 System: 0.0 s, 0.0 s.
545 System: 0.0 s, 0.0 s.
546
546
547 -d
547 -d
548 run your program under the control of pdb, the Python debugger.
548 run your program under the control of pdb, the Python debugger.
549 This allows you to execute your program step by step, watch variables,
549 This allows you to execute your program step by step, watch variables,
550 etc. Internally, what IPython does is similar to calling::
550 etc. Internally, what IPython does is similar to calling::
551
551
552 pdb.run('execfile("YOURFILENAME")')
552 pdb.run('execfile("YOURFILENAME")')
553
553
554 with a breakpoint set on line 1 of your file. You can change the line
554 with a breakpoint set on line 1 of your file. You can change the line
555 number for this automatic breakpoint to be <N> by using the -bN option
555 number for this automatic breakpoint to be <N> by using the -bN option
556 (where N must be an integer). For example::
556 (where N must be an integer). For example::
557
557
558 %run -d -b40 myscript
558 %run -d -b40 myscript
559
559
560 will set the first breakpoint at line 40 in myscript.py. Note that
560 will set the first breakpoint at line 40 in myscript.py. Note that
561 the first breakpoint must be set on a line which actually does
561 the first breakpoint must be set on a line which actually does
562 something (not a comment or docstring) for it to stop execution.
562 something (not a comment or docstring) for it to stop execution.
563
563
564 Or you can specify a breakpoint in a different file::
564 Or you can specify a breakpoint in a different file::
565
565
566 %run -d -b myotherfile.py:20 myscript
566 %run -d -b myotherfile.py:20 myscript
567
567
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
568 When the pdb debugger starts, you will see a (Pdb) prompt. You must
569 first enter 'c' (without quotes) to start execution up to the first
569 first enter 'c' (without quotes) to start execution up to the first
570 breakpoint.
570 breakpoint.
571
571
572 Entering 'help' gives information about the use of the debugger. You
572 Entering 'help' gives information about the use of the debugger. You
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
573 can easily see pdb's full documentation with "import pdb;pdb.help()"
574 at a prompt.
574 at a prompt.
575
575
576 -p
576 -p
577 run program under the control of the Python profiler module (which
577 run program under the control of the Python profiler module (which
578 prints a detailed report of execution times, function calls, etc).
578 prints a detailed report of execution times, function calls, etc).
579
579
580 You can pass other options after -p which affect the behavior of the
580 You can pass other options after -p which affect the behavior of the
581 profiler itself. See the docs for %prun for details.
581 profiler itself. See the docs for %prun for details.
582
582
583 In this mode, the program's variables do NOT propagate back to the
583 In this mode, the program's variables do NOT propagate back to the
584 IPython interactive namespace (because they remain in the namespace
584 IPython interactive namespace (because they remain in the namespace
585 where the profiler executes them).
585 where the profiler executes them).
586
586
587 Internally this triggers a call to %prun, see its documentation for
587 Internally this triggers a call to %prun, see its documentation for
588 details on the options available specifically for profiling.
588 details on the options available specifically for profiling.
589
589
590 There is one special usage for which the text above doesn't apply:
590 There is one special usage for which the text above doesn't apply:
591 if the filename ends with .ipy[nb], the file is run as ipython script,
591 if the filename ends with .ipy[nb], the file is run as ipython script,
592 just as if the commands were written on IPython prompt.
592 just as if the commands were written on IPython prompt.
593
593
594 -m
594 -m
595 specify module name to load instead of script path. Similar to
595 specify module name to load instead of script path. Similar to
596 the -m option for the python interpreter. Use this option last if you
596 the -m option for the python interpreter. Use this option last if you
597 want to combine with other %run options. Unlike the python interpreter
597 want to combine with other %run options. Unlike the python interpreter
598 only source modules are allowed no .pyc or .pyo files.
598 only source modules are allowed no .pyc or .pyo files.
599 For example::
599 For example::
600
600
601 %run -m example
601 %run -m example
602
602
603 will run the example module.
603 will run the example module.
604
604
605 -G
605 -G
606 disable shell-like glob expansion of arguments.
606 disable shell-like glob expansion of arguments.
607
607
608 """
608 """
609
609
610 # get arguments and set sys.argv for program to be run.
610 # get arguments and set sys.argv for program to be run.
611 opts, arg_lst = self.parse_options(parameter_s,
611 opts, arg_lst = self.parse_options(parameter_s,
612 'nidtN:b:pD:l:rs:T:em:G',
612 'nidtN:b:pD:l:rs:T:em:G',
613 mode='list', list_all=1)
613 mode='list', list_all=1)
614 if "m" in opts:
614 if "m" in opts:
615 modulename = opts["m"][0]
615 modulename = opts["m"][0]
616 modpath = find_mod(modulename)
616 modpath = find_mod(modulename)
617 if modpath is None:
617 if modpath is None:
618 warn('%r is not a valid modulename on sys.path'%modulename)
618 warn('%r is not a valid modulename on sys.path'%modulename)
619 return
619 return
620 arg_lst = [modpath] + arg_lst
620 arg_lst = [modpath] + arg_lst
621 try:
621 try:
622 filename = file_finder(arg_lst[0])
622 filename = file_finder(arg_lst[0])
623 except IndexError:
623 except IndexError:
624 warn('you must provide at least a filename.')
624 warn('you must provide at least a filename.')
625 print('\n%run:\n', oinspect.getdoc(self.run))
625 print('\n%run:\n', oinspect.getdoc(self.run))
626 return
626 return
627 except IOError as e:
627 except IOError as e:
628 try:
628 try:
629 msg = str(e)
629 msg = str(e)
630 except UnicodeError:
630 except UnicodeError:
631 msg = e.message
631 msg = e.message
632 error(msg)
632 error(msg)
633 return
633 return
634
634
635 if filename.lower().endswith(('.ipy', '.ipynb')):
635 if filename.lower().endswith(('.ipy', '.ipynb')):
636 with preserve_keys(self.shell.user_ns, '__file__'):
636 with preserve_keys(self.shell.user_ns, '__file__'):
637 self.shell.user_ns['__file__'] = filename
637 self.shell.user_ns['__file__'] = filename
638 self.shell.safe_execfile_ipy(filename)
638 self.shell.safe_execfile_ipy(filename)
639 return
639 return
640
640
641 # Control the response to exit() calls made by the script being run
641 # Control the response to exit() calls made by the script being run
642 exit_ignore = 'e' in opts
642 exit_ignore = 'e' in opts
643
643
644 # Make sure that the running script gets a proper sys.argv as if it
644 # Make sure that the running script gets a proper sys.argv as if it
645 # were run from a system shell.
645 # were run from a system shell.
646 save_argv = sys.argv # save it for later restoring
646 save_argv = sys.argv # save it for later restoring
647
647
648 if 'G' in opts:
648 if 'G' in opts:
649 args = arg_lst[1:]
649 args = arg_lst[1:]
650 else:
650 else:
651 # tilde and glob expansion
651 # tilde and glob expansion
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
652 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
653
653
654 sys.argv = [filename] + args # put in the proper filename
654 sys.argv = [filename] + args # put in the proper filename
655 # protect sys.argv from potential unicode strings on Python 2:
655 # protect sys.argv from potential unicode strings on Python 2:
656 if not py3compat.PY3:
656 if not py3compat.PY3:
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
657 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
658
658
659 if 'i' in opts:
659 if 'i' in opts:
660 # Run in user's interactive namespace
660 # Run in user's interactive namespace
661 prog_ns = self.shell.user_ns
661 prog_ns = self.shell.user_ns
662 __name__save = self.shell.user_ns['__name__']
662 __name__save = self.shell.user_ns['__name__']
663 prog_ns['__name__'] = '__main__'
663 prog_ns['__name__'] = '__main__'
664 main_mod = self.shell.user_module
664 main_mod = self.shell.user_module
665
665
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
666 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
667 # set the __file__ global in the script's namespace
667 # set the __file__ global in the script's namespace
668 # TK: Is this necessary in interactive mode?
668 # TK: Is this necessary in interactive mode?
669 prog_ns['__file__'] = filename
669 prog_ns['__file__'] = filename
670 else:
670 else:
671 # Run in a fresh, empty namespace
671 # Run in a fresh, empty namespace
672 if 'n' in opts:
672 if 'n' in opts:
673 name = os.path.splitext(os.path.basename(filename))[0]
673 name = os.path.splitext(os.path.basename(filename))[0]
674 else:
674 else:
675 name = '__main__'
675 name = '__main__'
676
676
677 # The shell MUST hold a reference to prog_ns so after %run
677 # The shell MUST hold a reference to prog_ns so after %run
678 # exits, the python deletion mechanism doesn't zero it out
678 # exits, the python deletion mechanism doesn't zero it out
679 # (leaving dangling references). See interactiveshell for details
679 # (leaving dangling references). See interactiveshell for details
680 main_mod = self.shell.new_main_mod(filename, name)
680 main_mod = self.shell.new_main_mod(filename, name)
681 prog_ns = main_mod.__dict__
681 prog_ns = main_mod.__dict__
682
682
683 # pickle fix. See interactiveshell for an explanation. But we need to
683 # pickle fix. See interactiveshell for an explanation. But we need to
684 # make sure that, if we overwrite __main__, we replace it at the end
684 # make sure that, if we overwrite __main__, we replace it at the end
685 main_mod_name = prog_ns['__name__']
685 main_mod_name = prog_ns['__name__']
686
686
687 if main_mod_name == '__main__':
687 if main_mod_name == '__main__':
688 restore_main = sys.modules['__main__']
688 restore_main = sys.modules['__main__']
689 else:
689 else:
690 restore_main = False
690 restore_main = False
691
691
692 # This needs to be undone at the end to prevent holding references to
692 # This needs to be undone at the end to prevent holding references to
693 # every single object ever created.
693 # every single object ever created.
694 sys.modules[main_mod_name] = main_mod
694 sys.modules[main_mod_name] = main_mod
695
695
696 if 'p' in opts or 'd' in opts:
696 if 'p' in opts or 'd' in opts:
697 if 'm' in opts:
697 if 'm' in opts:
698 code = 'run_module(modulename, prog_ns)'
698 code = 'run_module(modulename, prog_ns)'
699 code_ns = {
699 code_ns = {
700 'run_module': self.shell.safe_run_module,
700 'run_module': self.shell.safe_run_module,
701 'prog_ns': prog_ns,
701 'prog_ns': prog_ns,
702 'modulename': modulename,
702 'modulename': modulename,
703 }
703 }
704 else:
704 else:
705 if 'd' in opts:
705 if 'd' in opts:
706 # allow exceptions to raise in debug mode
706 # allow exceptions to raise in debug mode
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
707 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
708 else:
708 else:
709 code = 'execfile(filename, prog_ns)'
709 code = 'execfile(filename, prog_ns)'
710 code_ns = {
710 code_ns = {
711 'execfile': self.shell.safe_execfile,
711 'execfile': self.shell.safe_execfile,
712 'prog_ns': prog_ns,
712 'prog_ns': prog_ns,
713 'filename': get_py_filename(filename),
713 'filename': get_py_filename(filename),
714 }
714 }
715
715
716 try:
716 try:
717 stats = None
717 stats = None
718 if 'p' in opts:
718 if 'p' in opts:
719 stats = self._run_with_profiler(code, opts, code_ns)
719 stats = self._run_with_profiler(code, opts, code_ns)
720 else:
720 else:
721 if 'd' in opts:
721 if 'd' in opts:
722 bp_file, bp_line = parse_breakpoint(
722 bp_file, bp_line = parse_breakpoint(
723 opts.get('b', ['1'])[0], filename)
723 opts.get('b', ['1'])[0], filename)
724 self._run_with_debugger(
724 self._run_with_debugger(
725 code, code_ns, filename, bp_line, bp_file)
725 code, code_ns, filename, bp_line, bp_file)
726 else:
726 else:
727 if 'm' in opts:
727 if 'm' in opts:
728 def run():
728 def run():
729 self.shell.safe_run_module(modulename, prog_ns)
729 self.shell.safe_run_module(modulename, prog_ns)
730 else:
730 else:
731 if runner is None:
731 if runner is None:
732 runner = self.default_runner
732 runner = self.default_runner
733 if runner is None:
733 if runner is None:
734 runner = self.shell.safe_execfile
734 runner = self.shell.safe_execfile
735
735
736 def run():
736 def run():
737 runner(filename, prog_ns, prog_ns,
737 runner(filename, prog_ns, prog_ns,
738 exit_ignore=exit_ignore)
738 exit_ignore=exit_ignore)
739
739
740 if 't' in opts:
740 if 't' in opts:
741 # timed execution
741 # timed execution
742 try:
742 try:
743 nruns = int(opts['N'][0])
743 nruns = int(opts['N'][0])
744 if nruns < 1:
744 if nruns < 1:
745 error('Number of runs must be >=1')
745 error('Number of runs must be >=1')
746 return
746 return
747 except (KeyError):
747 except (KeyError):
748 nruns = 1
748 nruns = 1
749 self._run_with_timing(run, nruns)
749 self._run_with_timing(run, nruns)
750 else:
750 else:
751 # regular execution
751 # regular execution
752 run()
752 run()
753
753
754 if 'i' in opts:
754 if 'i' in opts:
755 self.shell.user_ns['__name__'] = __name__save
755 self.shell.user_ns['__name__'] = __name__save
756 else:
756 else:
757 # update IPython interactive namespace
757 # update IPython interactive namespace
758
758
759 # Some forms of read errors on the file may mean the
759 # Some forms of read errors on the file may mean the
760 # __name__ key was never set; using pop we don't have to
760 # __name__ key was never set; using pop we don't have to
761 # worry about a possible KeyError.
761 # worry about a possible KeyError.
762 prog_ns.pop('__name__', None)
762 prog_ns.pop('__name__', None)
763
763
764 with preserve_keys(self.shell.user_ns, '__file__'):
764 with preserve_keys(self.shell.user_ns, '__file__'):
765 self.shell.user_ns.update(prog_ns)
765 self.shell.user_ns.update(prog_ns)
766 finally:
766 finally:
767 # It's a bit of a mystery why, but __builtins__ can change from
767 # It's a bit of a mystery why, but __builtins__ can change from
768 # being a module to becoming a dict missing some key data after
768 # being a module to becoming a dict missing some key data after
769 # %run. As best I can see, this is NOT something IPython is doing
769 # %run. As best I can see, this is NOT something IPython is doing
770 # at all, and similar problems have been reported before:
770 # at all, and similar problems have been reported before:
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
771 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
772 # Since this seems to be done by the interpreter itself, the best
772 # Since this seems to be done by the interpreter itself, the best
773 # we can do is to at least restore __builtins__ for the user on
773 # we can do is to at least restore __builtins__ for the user on
774 # exit.
774 # exit.
775 self.shell.user_ns['__builtins__'] = builtin_mod
775 self.shell.user_ns['__builtins__'] = builtin_mod
776
776
777 # Ensure key global structures are restored
777 # Ensure key global structures are restored
778 sys.argv = save_argv
778 sys.argv = save_argv
779 if restore_main:
779 if restore_main:
780 sys.modules['__main__'] = restore_main
780 sys.modules['__main__'] = restore_main
781 else:
781 else:
782 # Remove from sys.modules the reference to main_mod we'd
782 # Remove from sys.modules the reference to main_mod we'd
783 # added. Otherwise it will trap references to objects
783 # added. Otherwise it will trap references to objects
784 # contained therein.
784 # contained therein.
785 del sys.modules[main_mod_name]
785 del sys.modules[main_mod_name]
786
786
787 return stats
787 return stats
788
788
789 def _run_with_debugger(self, code, code_ns, filename=None,
789 def _run_with_debugger(self, code, code_ns, filename=None,
790 bp_line=None, bp_file=None):
790 bp_line=None, bp_file=None):
791 """
791 """
792 Run `code` in debugger with a break point.
792 Run `code` in debugger with a break point.
793
793
794 Parameters
794 Parameters
795 ----------
795 ----------
796 code : str
796 code : str
797 Code to execute.
797 Code to execute.
798 code_ns : dict
798 code_ns : dict
799 A namespace in which `code` is executed.
799 A namespace in which `code` is executed.
800 filename : str
800 filename : str
801 `code` is ran as if it is in `filename`.
801 `code` is ran as if it is in `filename`.
802 bp_line : int, optional
802 bp_line : int, optional
803 Line number of the break point.
803 Line number of the break point.
804 bp_file : str, optional
804 bp_file : str, optional
805 Path to the file in which break point is specified.
805 Path to the file in which break point is specified.
806 `filename` is used if not given.
806 `filename` is used if not given.
807
807
808 Raises
808 Raises
809 ------
809 ------
810 UsageError
810 UsageError
811 If the break point given by `bp_line` is not valid.
811 If the break point given by `bp_line` is not valid.
812
812
813 """
813 """
814 deb = self.shell.InteractiveTB.pdb
814 deb = self.shell.InteractiveTB.pdb
815 if not deb:
815 if not deb:
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
816 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
817 deb = self.shell.InteractiveTB.pdb
817 deb = self.shell.InteractiveTB.pdb
818
818
819 # deb.checkline() fails if deb.curframe exists but is None; it can
819 # deb.checkline() fails if deb.curframe exists but is None; it can
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
820 # handle it not existing. https://github.com/ipython/ipython/issues/10028
821 if hasattr(deb, 'curframe'):
821 if hasattr(deb, 'curframe'):
822 del deb.curframe
822 del deb.curframe
823
823
824 # reset Breakpoint state, which is moronically kept
824 # reset Breakpoint state, which is moronically kept
825 # in a class
825 # in a class
826 bdb.Breakpoint.next = 1
826 bdb.Breakpoint.next = 1
827 bdb.Breakpoint.bplist = {}
827 bdb.Breakpoint.bplist = {}
828 bdb.Breakpoint.bpbynumber = [None]
828 bdb.Breakpoint.bpbynumber = [None]
829 if bp_line is not None:
829 if bp_line is not None:
830 # Set an initial breakpoint to stop execution
830 # Set an initial breakpoint to stop execution
831 maxtries = 10
831 maxtries = 10
832 bp_file = bp_file or filename
832 bp_file = bp_file or filename
833 checkline = deb.checkline(bp_file, bp_line)
833 checkline = deb.checkline(bp_file, bp_line)
834 if not checkline:
834 if not checkline:
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
835 for bp in range(bp_line + 1, bp_line + maxtries + 1):
836 if deb.checkline(bp_file, bp):
836 if deb.checkline(bp_file, bp):
837 break
837 break
838 else:
838 else:
839 msg = ("\nI failed to find a valid line to set "
839 msg = ("\nI failed to find a valid line to set "
840 "a breakpoint\n"
840 "a breakpoint\n"
841 "after trying up to line: %s.\n"
841 "after trying up to line: %s.\n"
842 "Please set a valid breakpoint manually "
842 "Please set a valid breakpoint manually "
843 "with the -b option." % bp)
843 "with the -b option." % bp)
844 raise UsageError(msg)
844 raise UsageError(msg)
845 # if we find a good linenumber, set the breakpoint
845 # if we find a good linenumber, set the breakpoint
846 deb.do_break('%s:%s' % (bp_file, bp_line))
846 deb.do_break('%s:%s' % (bp_file, bp_line))
847
847
848 if filename:
848 if filename:
849 # Mimic Pdb._runscript(...)
849 # Mimic Pdb._runscript(...)
850 deb._wait_for_mainpyfile = True
850 deb._wait_for_mainpyfile = True
851 deb.mainpyfile = deb.canonic(filename)
851 deb.mainpyfile = deb.canonic(filename)
852
852
853 # Start file run
853 # Start file run
854 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
854 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
855 try:
855 try:
856 if filename:
856 if filename:
857 # save filename so it can be used by methods on the deb object
857 # save filename so it can be used by methods on the deb object
858 deb._exec_filename = filename
858 deb._exec_filename = filename
859 while True:
859 while True:
860 try:
860 try:
861 deb.run(code, code_ns)
861 deb.run(code, code_ns)
862 except Restart:
862 except Restart:
863 print("Restarting")
863 print("Restarting")
864 if filename:
864 if filename:
865 deb._wait_for_mainpyfile = True
865 deb._wait_for_mainpyfile = True
866 deb.mainpyfile = deb.canonic(filename)
866 deb.mainpyfile = deb.canonic(filename)
867 continue
867 continue
868 else:
868 else:
869 break
869 break
870
870
871
871
872 except:
872 except:
873 etype, value, tb = sys.exc_info()
873 etype, value, tb = sys.exc_info()
874 # Skip three frames in the traceback: the %run one,
874 # Skip three frames in the traceback: the %run one,
875 # one inside bdb.py, and the command-line typed by the
875 # one inside bdb.py, and the command-line typed by the
876 # user (run by exec in pdb itself).
876 # user (run by exec in pdb itself).
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
877 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
878
878
879 @staticmethod
879 @staticmethod
880 def _run_with_timing(run, nruns):
880 def _run_with_timing(run, nruns):
881 """
881 """
882 Run function `run` and print timing information.
882 Run function `run` and print timing information.
883
883
884 Parameters
884 Parameters
885 ----------
885 ----------
886 run : callable
886 run : callable
887 Any callable object which takes no argument.
887 Any callable object which takes no argument.
888 nruns : int
888 nruns : int
889 Number of times to execute `run`.
889 Number of times to execute `run`.
890
890
891 """
891 """
892 twall0 = time.time()
892 twall0 = time.time()
893 if nruns == 1:
893 if nruns == 1:
894 t0 = clock2()
894 t0 = clock2()
895 run()
895 run()
896 t1 = clock2()
896 t1 = clock2()
897 t_usr = t1[0] - t0[0]
897 t_usr = t1[0] - t0[0]
898 t_sys = t1[1] - t0[1]
898 t_sys = t1[1] - t0[1]
899 print("\nIPython CPU timings (estimated):")
899 print("\nIPython CPU timings (estimated):")
900 print(" User : %10.2f s." % t_usr)
900 print(" User : %10.2f s." % t_usr)
901 print(" System : %10.2f s." % t_sys)
901 print(" System : %10.2f s." % t_sys)
902 else:
902 else:
903 runs = range(nruns)
903 runs = range(nruns)
904 t0 = clock2()
904 t0 = clock2()
905 for nr in runs:
905 for nr in runs:
906 run()
906 run()
907 t1 = clock2()
907 t1 = clock2()
908 t_usr = t1[0] - t0[0]
908 t_usr = t1[0] - t0[0]
909 t_sys = t1[1] - t0[1]
909 t_sys = t1[1] - t0[1]
910 print("\nIPython CPU timings (estimated):")
910 print("\nIPython CPU timings (estimated):")
911 print("Total runs performed:", nruns)
911 print("Total runs performed:", nruns)
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
912 print(" Times : %10s %10s" % ('Total', 'Per run'))
913 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
913 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
914 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
914 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
915 twall1 = time.time()
915 twall1 = time.time()
916 print("Wall time: %10.2f s." % (twall1 - twall0))
916 print("Wall time: %10.2f s." % (twall1 - twall0))
917
917
918 @skip_doctest
918 @skip_doctest
919 @line_cell_magic
919 @line_cell_magic
920 def timeit(self, line='', cell=None):
920 def timeit(self, line='', cell=None):
921 """Time execution of a Python statement or expression
921 """Time execution of a Python statement or expression
922
922
923 Usage, in line mode:
923 Usage, in line mode:
924 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
924 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
925 or in cell mode:
925 or in cell mode:
926 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
926 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
927 code
927 code
928 code...
928 code...
929
929
930 Time execution of a Python statement or expression using the timeit
930 Time execution of a Python statement or expression using the timeit
931 module. This function can be used both as a line and cell magic:
931 module. This function can be used both as a line and cell magic:
932
932
933 - In line mode you can time a single-line statement (though multiple
933 - In line mode you can time a single-line statement (though multiple
934 ones can be chained with using semicolons).
934 ones can be chained with using semicolons).
935
935
936 - In cell mode, the statement in the first line is used as setup code
936 - In cell mode, the statement in the first line is used as setup code
937 (executed but not timed) and the body of the cell is timed. The cell
937 (executed but not timed) and the body of the cell is timed. The cell
938 body has access to any variables created in the setup code.
938 body has access to any variables created in the setup code.
939
939
940 Options:
940 Options:
941 -n<N>: execute the given statement <N> times in a loop. If this value
941 -n<N>: execute the given statement <N> times in a loop. If this value
942 is not given, a fitting value is chosen.
942 is not given, a fitting value is chosen.
943
943
944 -r<R>: repeat the loop iteration <R> times and take the best result.
944 -r<R>: repeat the loop iteration <R> times and take the best result.
945 Default: 3
945 Default: 3
946
946
947 -t: use time.time to measure the time, which is the default on Unix.
947 -t: use time.time to measure the time, which is the default on Unix.
948 This function measures wall time.
948 This function measures wall time.
949
949
950 -c: use time.clock to measure the time, which is the default on
950 -c: use time.clock to measure the time, which is the default on
951 Windows and measures wall time. On Unix, resource.getrusage is used
951 Windows and measures wall time. On Unix, resource.getrusage is used
952 instead and returns the CPU user time.
952 instead and returns the CPU user time.
953
953
954 -p<P>: use a precision of <P> digits to display the timing result.
954 -p<P>: use a precision of <P> digits to display the timing result.
955 Default: 3
955 Default: 3
956
956
957 -q: Quiet, do not print result.
957 -q: Quiet, do not print result.
958
958
959 -o: return a TimeitResult that can be stored in a variable to inspect
959 -o: return a TimeitResult that can be stored in a variable to inspect
960 the result in more details.
960 the result in more details.
961
961
962
962
963 Examples
963 Examples
964 --------
964 --------
965 ::
965 ::
966
966
967 In [1]: %timeit pass
967 In [1]: %timeit pass
968 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
968 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
969
969
970 In [2]: u = None
970 In [2]: u = None
971
971
972 In [3]: %timeit u is None
972 In [3]: %timeit u is None
973 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
973 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
974
974
975 In [4]: %timeit -r 4 u == None
975 In [4]: %timeit -r 4 u == None
976 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
976 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
977
977
978 In [5]: import time
978 In [5]: import time
979
979
980 In [6]: %timeit -n1 time.sleep(2)
980 In [6]: %timeit -n1 time.sleep(2)
981 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
981 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
982
982
983
983
984 The times reported by %timeit will be slightly higher than those
984 The times reported by %timeit will be slightly higher than those
985 reported by the timeit.py script when variables are accessed. This is
985 reported by the timeit.py script when variables are accessed. This is
986 due to the fact that %timeit executes the statement in the namespace
986 due to the fact that %timeit executes the statement in the namespace
987 of the shell, compared with timeit.py, which uses a single setup
987 of the shell, compared with timeit.py, which uses a single setup
988 statement to import function or create variables. Generally, the bias
988 statement to import function or create variables. Generally, the bias
989 does not matter as long as results from timeit.py are not mixed with
989 does not matter as long as results from timeit.py are not mixed with
990 those from %timeit."""
990 those from %timeit."""
991
991
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
992 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
993 posix=False, strict=False)
993 posix=False, strict=False)
994 if stmt == "" and cell is None:
994 if stmt == "" and cell is None:
995 return
995 return
996
996
997 timefunc = timeit.default_timer
997 timefunc = timeit.default_timer
998 number = int(getattr(opts, "n", 0))
998 number = int(getattr(opts, "n", 0))
999 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
999 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1000 repeat = int(getattr(opts, "r", default_repeat))
1000 repeat = int(getattr(opts, "r", default_repeat))
1001 precision = int(getattr(opts, "p", 3))
1001 precision = int(getattr(opts, "p", 3))
1002 quiet = 'q' in opts
1002 quiet = 'q' in opts
1003 return_result = 'o' in opts
1003 return_result = 'o' in opts
1004 if hasattr(opts, "t"):
1004 if hasattr(opts, "t"):
1005 timefunc = time.time
1005 timefunc = time.time
1006 if hasattr(opts, "c"):
1006 if hasattr(opts, "c"):
1007 timefunc = clock
1007 timefunc = clock
1008
1008
1009 timer = Timer(timer=timefunc)
1009 timer = Timer(timer=timefunc)
1010 # this code has tight coupling to the inner workings of timeit.Timer,
1010 # this code has tight coupling to the inner workings of timeit.Timer,
1011 # but is there a better way to achieve that the code stmt has access
1011 # but is there a better way to achieve that the code stmt has access
1012 # to the shell namespace?
1012 # to the shell namespace?
1013 transform = self.shell.input_splitter.transform_cell
1013 transform = self.shell.input_splitter.transform_cell
1014
1014
1015 if cell is None:
1015 if cell is None:
1016 # called as line magic
1016 # called as line magic
1017 ast_setup = self.shell.compile.ast_parse("pass")
1017 ast_setup = self.shell.compile.ast_parse("pass")
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1018 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1019 else:
1019 else:
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1020 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1021 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1022
1022
1023 ast_setup = self.shell.transform_ast(ast_setup)
1023 ast_setup = self.shell.transform_ast(ast_setup)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1024 ast_stmt = self.shell.transform_ast(ast_stmt)
1025
1025
1026 # This codestring is taken from timeit.template - we fill it in as an
1026 # This codestring is taken from timeit.template - we fill it in as an
1027 # AST, so that we can apply our AST transformations to the user code
1027 # AST, so that we can apply our AST transformations to the user code
1028 # without affecting the timing code.
1028 # without affecting the timing code.
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1029 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1030 ' setup\n'
1030 ' setup\n'
1031 ' _t0 = _timer()\n'
1031 ' _t0 = _timer()\n'
1032 ' for _i in _it:\n'
1032 ' for _i in _it:\n'
1033 ' stmt\n'
1033 ' stmt\n'
1034 ' _t1 = _timer()\n'
1034 ' _t1 = _timer()\n'
1035 ' return _t1 - _t0\n')
1035 ' return _t1 - _t0\n')
1036
1036
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1037 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1038 timeit_ast = ast.fix_missing_locations(timeit_ast)
1039
1039
1040 # Track compilation time so it can be reported if too long
1040 # Track compilation time so it can be reported if too long
1041 # Minimum time above which compilation time will be reported
1041 # Minimum time above which compilation time will be reported
1042 tc_min = 0.1
1042 tc_min = 0.1
1043
1043
1044 t0 = clock()
1044 t0 = clock()
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1045 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1046 tc = clock()-t0
1046 tc = clock()-t0
1047
1047
1048 ns = {}
1048 ns = {}
1049 exec(code, self.shell.user_ns, ns)
1049 exec(code, self.shell.user_ns, ns)
1050 timer.inner = ns["inner"]
1050 timer.inner = ns["inner"]
1051
1051
1052 # This is used to check if there is a huge difference between the
1052 # This is used to check if there is a huge difference between the
1053 # best and worst timings.
1053 # best and worst timings.
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1054 # Issue: https://github.com/ipython/ipython/issues/6471
1055 if number == 0:
1055 if number == 0:
1056 # determine number so that 0.2 <= total time < 2.0
1056 # determine number so that 0.2 <= total time < 2.0
1057 for index in range(0, 10):
1057 for index in range(0, 10):
1058 number = 10 ** index
1058 number = 10 ** index
1059 time_number = timer.timeit(number)
1059 time_number = timer.timeit(number)
1060 if time_number >= 0.2:
1060 if time_number >= 0.2:
1061 break
1061 break
1062
1062
1063 all_runs = timer.repeat(repeat, number)
1063 all_runs = timer.repeat(repeat, number)
1064 best = min(all_runs) / number
1064 best = min(all_runs) / number
1065 worst = max(all_runs) / number
1065 worst = max(all_runs) / number
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1066 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1067
1067
1068 if not quiet :
1068 if not quiet :
1069 # Check best timing is greater than zero to avoid a
1069 # Check best timing is greater than zero to avoid a
1070 # ZeroDivisionError.
1070 # ZeroDivisionError.
1071 # In cases where the slowest timing is lesser than a micosecond
1071 # In cases where the slowest timing is lesser than a micosecond
1072 # we assume that it does not really matter if the fastest
1072 # we assume that it does not really matter if the fastest
1073 # timing is 4 times faster than the slowest timing or not.
1073 # timing is 4 times faster than the slowest timing or not.
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1074 if worst > 4 * best and best > 0 and worst > 1e-6:
1075 print("The slowest run took %0.2f times longer than the "
1075 print("The slowest run took %0.2f times longer than the "
1076 "fastest. This could mean that an intermediate result "
1076 "fastest. This could mean that an intermediate result "
1077 "is being cached." % (worst / best))
1077 "is being cached." % (worst / best))
1078
1078
1079 print( timeit_result )
1079 print( timeit_result )
1080
1080
1081 if tc > tc_min:
1081 if tc > tc_min:
1082 print("Compiler time: %.2f s" % tc)
1082 print("Compiler time: %.2f s" % tc)
1083 if return_result:
1083 if return_result:
1084 return timeit_result
1084 return timeit_result
1085
1085
1086 @skip_doctest
1086 @skip_doctest
1087 @needs_local_scope
1087 @needs_local_scope
1088 @line_cell_magic
1088 @line_cell_magic
1089 def time(self,line='', cell=None, local_ns=None):
1089 def time(self,line='', cell=None, local_ns=None):
1090 """Time execution of a Python statement or expression.
1090 """Time execution of a Python statement or expression.
1091
1091
1092 The CPU and wall clock times are printed, and the value of the
1092 The CPU and wall clock times are printed, and the value of the
1093 expression (if any) is returned. Note that under Win32, system time
1093 expression (if any) is returned. Note that under Win32, system time
1094 is always reported as 0, since it can not be measured.
1094 is always reported as 0, since it can not be measured.
1095
1095
1096 This function can be used both as a line and cell magic:
1096 This function can be used both as a line and cell magic:
1097
1097
1098 - In line mode you can time a single-line statement (though multiple
1098 - In line mode you can time a single-line statement (though multiple
1099 ones can be chained with using semicolons).
1099 ones can be chained with using semicolons).
1100
1100
1101 - In cell mode, you can time the cell body (a directly
1101 - In cell mode, you can time the cell body (a directly
1102 following statement raises an error).
1102 following statement raises an error).
1103
1103
1104 This function provides very basic timing functionality. Use the timeit
1104 This function provides very basic timing functionality. Use the timeit
1105 magic for more control over the measurement.
1105 magic for more control over the measurement.
1106
1106
1107 Examples
1107 Examples
1108 --------
1108 --------
1109 ::
1109 ::
1110
1110
1111 In [1]: %time 2**128
1111 In [1]: %time 2**128
1112 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1112 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1113 Wall time: 0.00
1113 Wall time: 0.00
1114 Out[1]: 340282366920938463463374607431768211456L
1114 Out[1]: 340282366920938463463374607431768211456L
1115
1115
1116 In [2]: n = 1000000
1116 In [2]: n = 1000000
1117
1117
1118 In [3]: %time sum(range(n))
1118 In [3]: %time sum(range(n))
1119 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1119 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1120 Wall time: 1.37
1120 Wall time: 1.37
1121 Out[3]: 499999500000L
1121 Out[3]: 499999500000L
1122
1122
1123 In [4]: %time print 'hello world'
1123 In [4]: %time print 'hello world'
1124 hello world
1124 hello world
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1126 Wall time: 0.00
1126 Wall time: 0.00
1127
1127
1128 Note that the time needed by Python to compile the given expression
1128 Note that the time needed by Python to compile the given expression
1129 will be reported if it is more than 0.1s. In this example, the
1129 will be reported if it is more than 0.1s. In this example, the
1130 actual exponentiation is done by Python at compilation time, so while
1130 actual exponentiation is done by Python at compilation time, so while
1131 the expression can take a noticeable amount of time to compute, that
1131 the expression can take a noticeable amount of time to compute, that
1132 time is purely due to the compilation:
1132 time is purely due to the compilation:
1133
1133
1134 In [5]: %time 3**9999;
1134 In [5]: %time 3**9999;
1135 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1135 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1136 Wall time: 0.00 s
1136 Wall time: 0.00 s
1137
1137
1138 In [6]: %time 3**999999;
1138 In [6]: %time 3**999999;
1139 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1139 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1140 Wall time: 0.00 s
1140 Wall time: 0.00 s
1141 Compiler : 0.78 s
1141 Compiler : 0.78 s
1142 """
1142 """
1143
1143
1144 # fail immediately if the given expression can't be compiled
1144 # fail immediately if the given expression can't be compiled
1145
1145
1146 if line and cell:
1146 if line and cell:
1147 raise UsageError("Can't use statement directly after '%%time'!")
1147 raise UsageError("Can't use statement directly after '%%time'!")
1148
1148
1149 if cell:
1149 if cell:
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1150 expr = self.shell.input_transformer_manager.transform_cell(cell)
1151 else:
1151 else:
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1152 expr = self.shell.input_transformer_manager.transform_cell(line)
1153
1153
1154 # Minimum time above which parse time will be reported
1154 # Minimum time above which parse time will be reported
1155 tp_min = 0.1
1155 tp_min = 0.1
1156
1156
1157 t0 = clock()
1157 t0 = clock()
1158 expr_ast = self.shell.compile.ast_parse(expr)
1158 expr_ast = self.shell.compile.ast_parse(expr)
1159 tp = clock()-t0
1159 tp = clock()-t0
1160
1160
1161 # Apply AST transformations
1161 # Apply AST transformations
1162 expr_ast = self.shell.transform_ast(expr_ast)
1162 expr_ast = self.shell.transform_ast(expr_ast)
1163
1163
1164 # Minimum time above which compilation time will be reported
1164 # Minimum time above which compilation time will be reported
1165 tc_min = 0.1
1165 tc_min = 0.1
1166
1166
1167 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1167 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1168 mode = 'eval'
1168 mode = 'eval'
1169 source = '<timed eval>'
1169 source = '<timed eval>'
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1170 expr_ast = ast.Expression(expr_ast.body[0].value)
1171 else:
1171 else:
1172 mode = 'exec'
1172 mode = 'exec'
1173 source = '<timed exec>'
1173 source = '<timed exec>'
1174 t0 = clock()
1174 t0 = clock()
1175 code = self.shell.compile(expr_ast, source, mode)
1175 code = self.shell.compile(expr_ast, source, mode)
1176 tc = clock()-t0
1176 tc = clock()-t0
1177
1177
1178 # skew measurement as little as possible
1178 # skew measurement as little as possible
1179 glob = self.shell.user_ns
1179 glob = self.shell.user_ns
1180 wtime = time.time
1180 wtime = time.time
1181 # time execution
1181 # time execution
1182 wall_st = wtime()
1182 wall_st = wtime()
1183 if mode=='eval':
1183 if mode=='eval':
1184 st = clock2()
1184 st = clock2()
1185 out = eval(code, glob, local_ns)
1185 out = eval(code, glob, local_ns)
1186 end = clock2()
1186 end = clock2()
1187 else:
1187 else:
1188 st = clock2()
1188 st = clock2()
1189 exec(code, glob, local_ns)
1189 exec(code, glob, local_ns)
1190 end = clock2()
1190 end = clock2()
1191 out = None
1191 out = None
1192 wall_end = wtime()
1192 wall_end = wtime()
1193 # Compute actual times and report
1193 # Compute actual times and report
1194 wall_time = wall_end-wall_st
1194 wall_time = wall_end-wall_st
1195 cpu_user = end[0]-st[0]
1195 cpu_user = end[0]-st[0]
1196 cpu_sys = end[1]-st[1]
1196 cpu_sys = end[1]-st[1]
1197 cpu_tot = cpu_user+cpu_sys
1197 cpu_tot = cpu_user+cpu_sys
1198 # On windows cpu_sys is always zero, so no new information to the next print
1198 # On windows cpu_sys is always zero, so no new information to the next print
1199 if sys.platform != 'win32':
1199 if sys.platform != 'win32':
1200 print("CPU times: user %s, sys: %s, total: %s" % \
1200 print("CPU times: user %s, sys: %s, total: %s" % \
1201 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1201 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1202 print("Wall time: %s" % _format_time(wall_time))
1202 print("Wall time: %s" % _format_time(wall_time))
1203 if tc > tc_min:
1203 if tc > tc_min:
1204 print("Compiler : %s" % _format_time(tc))
1204 print("Compiler : %s" % _format_time(tc))
1205 if tp > tp_min:
1205 if tp > tp_min:
1206 print("Parser : %s" % _format_time(tp))
1206 print("Parser : %s" % _format_time(tp))
1207 return out
1207 return out
1208
1208
1209 @skip_doctest
1209 @skip_doctest
1210 @line_magic
1210 @line_magic
1211 def macro(self, parameter_s=''):
1211 def macro(self, parameter_s=''):
1212 """Define a macro for future re-execution. It accepts ranges of history,
1212 """Define a macro for future re-execution. It accepts ranges of history,
1213 filenames or string objects.
1213 filenames or string objects.
1214
1214
1215 Usage:\\
1215 Usage:\\
1216 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1216 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1217
1217
1218 Options:
1218 Options:
1219
1219
1220 -r: use 'raw' input. By default, the 'processed' history is used,
1220 -r: use 'raw' input. By default, the 'processed' history is used,
1221 so that magics are loaded in their transformed version to valid
1221 so that magics are loaded in their transformed version to valid
1222 Python. If this option is given, the raw input as typed at the
1222 Python. If this option is given, the raw input as typed at the
1223 command line is used instead.
1223 command line is used instead.
1224
1224
1225 -q: quiet macro definition. By default, a tag line is printed
1225 -q: quiet macro definition. By default, a tag line is printed
1226 to indicate the macro has been created, and then the contents of
1226 to indicate the macro has been created, and then the contents of
1227 the macro are printed. If this option is given, then no printout
1227 the macro are printed. If this option is given, then no printout
1228 is produced once the macro is created.
1228 is produced once the macro is created.
1229
1229
1230 This will define a global variable called `name` which is a string
1230 This will define a global variable called `name` which is a string
1231 made of joining the slices and lines you specify (n1,n2,... numbers
1231 made of joining the slices and lines you specify (n1,n2,... numbers
1232 above) from your input history into a single string. This variable
1232 above) from your input history into a single string. This variable
1233 acts like an automatic function which re-executes those lines as if
1233 acts like an automatic function which re-executes those lines as if
1234 you had typed them. You just type 'name' at the prompt and the code
1234 you had typed them. You just type 'name' at the prompt and the code
1235 executes.
1235 executes.
1236
1236
1237 The syntax for indicating input ranges is described in %history.
1237 The syntax for indicating input ranges is described in %history.
1238
1238
1239 Note: as a 'hidden' feature, you can also use traditional python slice
1239 Note: as a 'hidden' feature, you can also use traditional python slice
1240 notation, where N:M means numbers N through M-1.
1240 notation, where N:M means numbers N through M-1.
1241
1241
1242 For example, if your history contains (print using %hist -n )::
1242 For example, if your history contains (print using %hist -n )::
1243
1243
1244 44: x=1
1244 44: x=1
1245 45: y=3
1245 45: y=3
1246 46: z=x+y
1246 46: z=x+y
1247 47: print x
1247 47: print x
1248 48: a=5
1248 48: a=5
1249 49: print 'x',x,'y',y
1249 49: print 'x',x,'y',y
1250
1250
1251 you can create a macro with lines 44 through 47 (included) and line 49
1251 you can create a macro with lines 44 through 47 (included) and line 49
1252 called my_macro with::
1252 called my_macro with::
1253
1253
1254 In [55]: %macro my_macro 44-47 49
1254 In [55]: %macro my_macro 44-47 49
1255
1255
1256 Now, typing `my_macro` (without quotes) will re-execute all this code
1256 Now, typing `my_macro` (without quotes) will re-execute all this code
1257 in one pass.
1257 in one pass.
1258
1258
1259 You don't need to give the line-numbers in order, and any given line
1259 You don't need to give the line-numbers in order, and any given line
1260 number can appear multiple times. You can assemble macros with any
1260 number can appear multiple times. You can assemble macros with any
1261 lines from your input history in any order.
1261 lines from your input history in any order.
1262
1262
1263 The macro is a simple object which holds its value in an attribute,
1263 The macro is a simple object which holds its value in an attribute,
1264 but IPython's display system checks for macros and executes them as
1264 but IPython's display system checks for macros and executes them as
1265 code instead of printing them when you type their name.
1265 code instead of printing them when you type their name.
1266
1266
1267 You can view a macro's contents by explicitly printing it with::
1267 You can view a macro's contents by explicitly printing it with::
1268
1268
1269 print macro_name
1269 print macro_name
1270
1270
1271 """
1271 """
1272 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1272 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1273 if not args: # List existing macros
1273 if not args: # List existing macros
1274 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1274 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1275 isinstance(v, Macro))
1276 if len(args) == 1:
1275 if len(args) == 1:
1277 raise UsageError(
1276 raise UsageError(
1278 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1277 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1279 name, codefrom = args[0], " ".join(args[1:])
1278 name, codefrom = args[0], " ".join(args[1:])
1280
1279
1281 #print 'rng',ranges # dbg
1280 #print 'rng',ranges # dbg
1282 try:
1281 try:
1283 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1282 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1284 except (ValueError, TypeError) as e:
1283 except (ValueError, TypeError) as e:
1285 print(e.args[0])
1284 print(e.args[0])
1286 return
1285 return
1287 macro = Macro(lines)
1286 macro = Macro(lines)
1288 self.shell.define_macro(name, macro)
1287 self.shell.define_macro(name, macro)
1289 if not ( 'q' in opts) :
1288 if not ( 'q' in opts) :
1290 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1289 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1291 print('=== Macro contents: ===')
1290 print('=== Macro contents: ===')
1292 print(macro, end=' ')
1291 print(macro, end=' ')
1293
1292
1294 @magic_arguments.magic_arguments()
1293 @magic_arguments.magic_arguments()
1295 @magic_arguments.argument('output', type=str, default='', nargs='?',
1294 @magic_arguments.argument('output', type=str, default='', nargs='?',
1296 help="""The name of the variable in which to store output.
1295 help="""The name of the variable in which to store output.
1297 This is a utils.io.CapturedIO object with stdout/err attributes
1296 This is a utils.io.CapturedIO object with stdout/err attributes
1298 for the text of the captured output.
1297 for the text of the captured output.
1299
1298
1300 CapturedOutput also has a show() method for displaying the output,
1299 CapturedOutput also has a show() method for displaying the output,
1301 and __call__ as well, so you can use that to quickly display the
1300 and __call__ as well, so you can use that to quickly display the
1302 output.
1301 output.
1303
1302
1304 If unspecified, captured output is discarded.
1303 If unspecified, captured output is discarded.
1305 """
1304 """
1306 )
1305 )
1307 @magic_arguments.argument('--no-stderr', action="store_true",
1306 @magic_arguments.argument('--no-stderr', action="store_true",
1308 help="""Don't capture stderr."""
1307 help="""Don't capture stderr."""
1309 )
1308 )
1310 @magic_arguments.argument('--no-stdout', action="store_true",
1309 @magic_arguments.argument('--no-stdout', action="store_true",
1311 help="""Don't capture stdout."""
1310 help="""Don't capture stdout."""
1312 )
1311 )
1313 @magic_arguments.argument('--no-display', action="store_true",
1312 @magic_arguments.argument('--no-display', action="store_true",
1314 help="""Don't capture IPython's rich display."""
1313 help="""Don't capture IPython's rich display."""
1315 )
1314 )
1316 @cell_magic
1315 @cell_magic
1317 def capture(self, line, cell):
1316 def capture(self, line, cell):
1318 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1317 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1319 args = magic_arguments.parse_argstring(self.capture, line)
1318 args = magic_arguments.parse_argstring(self.capture, line)
1320 out = not args.no_stdout
1319 out = not args.no_stdout
1321 err = not args.no_stderr
1320 err = not args.no_stderr
1322 disp = not args.no_display
1321 disp = not args.no_display
1323 with capture_output(out, err, disp) as io:
1322 with capture_output(out, err, disp) as io:
1324 self.shell.run_cell(cell)
1323 self.shell.run_cell(cell)
1325 if args.output:
1324 if args.output:
1326 self.shell.user_ns[args.output] = io
1325 self.shell.user_ns[args.output] = io
1327
1326
1328 def parse_breakpoint(text, current_file):
1327 def parse_breakpoint(text, current_file):
1329 '''Returns (file, line) for file:line and (current_file, line) for line'''
1328 '''Returns (file, line) for file:line and (current_file, line) for line'''
1330 colon = text.find(':')
1329 colon = text.find(':')
1331 if colon == -1:
1330 if colon == -1:
1332 return current_file, int(text)
1331 return current_file, int(text)
1333 else:
1332 else:
1334 return text[:colon], int(text[colon+1:])
1333 return text[:colon], int(text[colon+1:])
1335
1334
1336 def _format_time(timespan, precision=3):
1335 def _format_time(timespan, precision=3):
1337 """Formats the timespan in a human readable form"""
1336 """Formats the timespan in a human readable form"""
1338
1337
1339 if timespan >= 60.0:
1338 if timespan >= 60.0:
1340 # we have more than a minute, format that in a human readable form
1339 # we have more than a minute, format that in a human readable form
1341 # Idea from http://snipplr.com/view/5713/
1340 # Idea from http://snipplr.com/view/5713/
1342 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1341 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1343 time = []
1342 time = []
1344 leftover = timespan
1343 leftover = timespan
1345 for suffix, length in parts:
1344 for suffix, length in parts:
1346 value = int(leftover / length)
1345 value = int(leftover / length)
1347 if value > 0:
1346 if value > 0:
1348 leftover = leftover % length
1347 leftover = leftover % length
1349 time.append(u'%s%s' % (str(value), suffix))
1348 time.append(u'%s%s' % (str(value), suffix))
1350 if leftover < 1:
1349 if leftover < 1:
1351 break
1350 break
1352 return " ".join(time)
1351 return " ".join(time)
1353
1352
1354
1353
1355 # Unfortunately the unicode 'micro' symbol can cause problems in
1354 # Unfortunately the unicode 'micro' symbol can cause problems in
1356 # certain terminals.
1355 # certain terminals.
1357 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1356 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1358 # Try to prevent crashes by being more secure than it needs to
1357 # Try to prevent crashes by being more secure than it needs to
1359 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1358 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1360 units = [u"s", u"ms",u'us',"ns"] # the save value
1359 units = [u"s", u"ms",u'us',"ns"] # the save value
1361 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1360 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1362 try:
1361 try:
1363 u'\xb5'.encode(sys.stdout.encoding)
1362 u'\xb5'.encode(sys.stdout.encoding)
1364 units = [u"s", u"ms",u'\xb5s',"ns"]
1363 units = [u"s", u"ms",u'\xb5s',"ns"]
1365 except:
1364 except:
1366 pass
1365 pass
1367 scaling = [1, 1e3, 1e6, 1e9]
1366 scaling = [1, 1e3, 1e6, 1e9]
1368
1367
1369 if timespan > 0.0:
1368 if timespan > 0.0:
1370 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1369 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1371 else:
1370 else:
1372 order = 3
1371 order = 3
1373 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1372 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,867 +1,866 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Python advanced pretty printer. This pretty printer is intended to
3 Python advanced pretty printer. This pretty printer is intended to
4 replace the old `pprint` python module which does not allow developers
4 replace the old `pprint` python module which does not allow developers
5 to provide their own pretty print callbacks.
5 to provide their own pretty print callbacks.
6
6
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8
8
9
9
10 Example Usage
10 Example Usage
11 -------------
11 -------------
12
12
13 To directly print the representation of an object use `pprint`::
13 To directly print the representation of an object use `pprint`::
14
14
15 from pretty import pprint
15 from pretty import pprint
16 pprint(complex_object)
16 pprint(complex_object)
17
17
18 To get a string of the output use `pretty`::
18 To get a string of the output use `pretty`::
19
19
20 from pretty import pretty
20 from pretty import pretty
21 string = pretty(complex_object)
21 string = pretty(complex_object)
22
22
23
23
24 Extending
24 Extending
25 ---------
25 ---------
26
26
27 The pretty library allows developers to add pretty printing rules for their
27 The pretty library allows developers to add pretty printing rules for their
28 own objects. This process is straightforward. All you have to do is to
28 own objects. This process is straightforward. All you have to do is to
29 add a `_repr_pretty_` method to your object and call the methods on the
29 add a `_repr_pretty_` method to your object and call the methods on the
30 pretty printer passed::
30 pretty printer passed::
31
31
32 class MyObject(object):
32 class MyObject(object):
33
33
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 ...
35 ...
36
36
37 Here is an example implementation of a `_repr_pretty_` method for a list
37 Here is an example implementation of a `_repr_pretty_` method for a list
38 subclass::
38 subclass::
39
39
40 class MyList(list):
40 class MyList(list):
41
41
42 def _repr_pretty_(self, p, cycle):
42 def _repr_pretty_(self, p, cycle):
43 if cycle:
43 if cycle:
44 p.text('MyList(...)')
44 p.text('MyList(...)')
45 else:
45 else:
46 with p.group(8, 'MyList([', '])'):
46 with p.group(8, 'MyList([', '])'):
47 for idx, item in enumerate(self):
47 for idx, item in enumerate(self):
48 if idx:
48 if idx:
49 p.text(',')
49 p.text(',')
50 p.breakable()
50 p.breakable()
51 p.pretty(item)
51 p.pretty(item)
52
52
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
54 react to that or the result is an infinite loop. `p.text()` just adds
54 react to that or the result is an infinite loop. `p.text()` just adds
55 non breaking text to the output, `p.breakable()` either adds a whitespace
55 non breaking text to the output, `p.breakable()` either adds a whitespace
56 or breaks here. If you pass it an argument it's used instead of the
56 or breaks here. If you pass it an argument it's used instead of the
57 default space. `p.pretty` prettyprints another object using the pretty print
57 default space. `p.pretty` prettyprints another object using the pretty print
58 method.
58 method.
59
59
60 The first parameter to the `group` function specifies the extra indentation
60 The first parameter to the `group` function specifies the extra indentation
61 of the next line. In this example the next item will either be on the same
61 of the next line. In this example the next item will either be on the same
62 line (if the items are short enough) or aligned with the right edge of the
62 line (if the items are short enough) or aligned with the right edge of the
63 opening bracket of `MyList`.
63 opening bracket of `MyList`.
64
64
65 If you just want to indent something you can use the group function
65 If you just want to indent something you can use the group function
66 without open / close parameters. You can also use this code::
66 without open / close parameters. You can also use this code::
67
67
68 with p.indent(2):
68 with p.indent(2):
69 ...
69 ...
70
70
71 Inheritance diagram:
71 Inheritance diagram:
72
72
73 .. inheritance-diagram:: IPython.lib.pretty
73 .. inheritance-diagram:: IPython.lib.pretty
74 :parts: 3
74 :parts: 3
75
75
76 :copyright: 2007 by Armin Ronacher.
76 :copyright: 2007 by Armin Ronacher.
77 Portions (c) 2009 by Robert Kern.
77 Portions (c) 2009 by Robert Kern.
78 :license: BSD License.
78 :license: BSD License.
79 """
79 """
80 from contextlib import contextmanager
80 from contextlib import contextmanager
81 import sys
81 import sys
82 import types
82 import types
83 import re
83 import re
84 import datetime
84 import datetime
85 from collections import deque
85 from collections import deque
86
86
87 from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
87 from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
88 from IPython.utils.encoding import get_stream_enc
88 from IPython.utils.encoding import get_stream_enc
89
89
90 from io import StringIO
90 from io import StringIO
91
91
92
92
93 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
93 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
94 'for_type', 'for_type_by_name']
94 'for_type', 'for_type_by_name']
95
95
96
96
97 MAX_SEQ_LENGTH = 1000
97 MAX_SEQ_LENGTH = 1000
98 _re_pattern_type = type(re.compile(''))
98 _re_pattern_type = type(re.compile(''))
99
99
100 def _safe_getattr(obj, attr, default=None):
100 def _safe_getattr(obj, attr, default=None):
101 """Safe version of getattr.
101 """Safe version of getattr.
102
102
103 Same as getattr, but will return ``default`` on any Exception,
103 Same as getattr, but will return ``default`` on any Exception,
104 rather than raising.
104 rather than raising.
105 """
105 """
106 try:
106 try:
107 return getattr(obj, attr, default)
107 return getattr(obj, attr, default)
108 except Exception:
108 except Exception:
109 return default
109 return default
110
110
111 if PY3:
111 if PY3:
112 CUnicodeIO = StringIO
112 CUnicodeIO = StringIO
113 else:
113 else:
114 class CUnicodeIO(StringIO):
114 class CUnicodeIO(StringIO):
115 """StringIO that casts str to unicode on Python 2"""
115 """StringIO that casts str to unicode on Python 2"""
116 def write(self, text):
116 def write(self, text):
117 return super(CUnicodeIO, self).write(
117 return super(CUnicodeIO, self).write(
118 cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
118 cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
119
119
120
120
121 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
121 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
122 """
122 """
123 Pretty print the object's representation.
123 Pretty print the object's representation.
124 """
124 """
125 stream = CUnicodeIO()
125 stream = CUnicodeIO()
126 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
126 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
127 printer.pretty(obj)
127 printer.pretty(obj)
128 printer.flush()
128 printer.flush()
129 return stream.getvalue()
129 return stream.getvalue()
130
130
131
131
132 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
132 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
133 """
133 """
134 Like `pretty` but print to stdout.
134 Like `pretty` but print to stdout.
135 """
135 """
136 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
136 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
137 printer.pretty(obj)
137 printer.pretty(obj)
138 printer.flush()
138 printer.flush()
139 sys.stdout.write(newline)
139 sys.stdout.write(newline)
140 sys.stdout.flush()
140 sys.stdout.flush()
141
141
142 class _PrettyPrinterBase(object):
142 class _PrettyPrinterBase(object):
143
143
144 @contextmanager
144 @contextmanager
145 def indent(self, indent):
145 def indent(self, indent):
146 """with statement support for indenting/dedenting."""
146 """with statement support for indenting/dedenting."""
147 self.indentation += indent
147 self.indentation += indent
148 try:
148 try:
149 yield
149 yield
150 finally:
150 finally:
151 self.indentation -= indent
151 self.indentation -= indent
152
152
153 @contextmanager
153 @contextmanager
154 def group(self, indent=0, open='', close=''):
154 def group(self, indent=0, open='', close=''):
155 """like begin_group / end_group but for the with statement."""
155 """like begin_group / end_group but for the with statement."""
156 self.begin_group(indent, open)
156 self.begin_group(indent, open)
157 try:
157 try:
158 yield
158 yield
159 finally:
159 finally:
160 self.end_group(indent, close)
160 self.end_group(indent, close)
161
161
162 class PrettyPrinter(_PrettyPrinterBase):
162 class PrettyPrinter(_PrettyPrinterBase):
163 """
163 """
164 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
164 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
165 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
165 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
166 this printer knows nothing about the default pprinters or the `_repr_pretty_`
166 this printer knows nothing about the default pprinters or the `_repr_pretty_`
167 callback method.
167 callback method.
168 """
168 """
169
169
170 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
170 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
171 self.output = output
171 self.output = output
172 self.max_width = max_width
172 self.max_width = max_width
173 self.newline = newline
173 self.newline = newline
174 self.max_seq_length = max_seq_length
174 self.max_seq_length = max_seq_length
175 self.output_width = 0
175 self.output_width = 0
176 self.buffer_width = 0
176 self.buffer_width = 0
177 self.buffer = deque()
177 self.buffer = deque()
178
178
179 root_group = Group(0)
179 root_group = Group(0)
180 self.group_stack = [root_group]
180 self.group_stack = [root_group]
181 self.group_queue = GroupQueue(root_group)
181 self.group_queue = GroupQueue(root_group)
182 self.indentation = 0
182 self.indentation = 0
183
183
184 def _break_outer_groups(self):
184 def _break_outer_groups(self):
185 while self.max_width < self.output_width + self.buffer_width:
185 while self.max_width < self.output_width + self.buffer_width:
186 group = self.group_queue.deq()
186 group = self.group_queue.deq()
187 if not group:
187 if not group:
188 return
188 return
189 while group.breakables:
189 while group.breakables:
190 x = self.buffer.popleft()
190 x = self.buffer.popleft()
191 self.output_width = x.output(self.output, self.output_width)
191 self.output_width = x.output(self.output, self.output_width)
192 self.buffer_width -= x.width
192 self.buffer_width -= x.width
193 while self.buffer and isinstance(self.buffer[0], Text):
193 while self.buffer and isinstance(self.buffer[0], Text):
194 x = self.buffer.popleft()
194 x = self.buffer.popleft()
195 self.output_width = x.output(self.output, self.output_width)
195 self.output_width = x.output(self.output, self.output_width)
196 self.buffer_width -= x.width
196 self.buffer_width -= x.width
197
197
198 def text(self, obj):
198 def text(self, obj):
199 """Add literal text to the output."""
199 """Add literal text to the output."""
200 width = len(obj)
200 width = len(obj)
201 if self.buffer:
201 if self.buffer:
202 text = self.buffer[-1]
202 text = self.buffer[-1]
203 if not isinstance(text, Text):
203 if not isinstance(text, Text):
204 text = Text()
204 text = Text()
205 self.buffer.append(text)
205 self.buffer.append(text)
206 text.add(obj, width)
206 text.add(obj, width)
207 self.buffer_width += width
207 self.buffer_width += width
208 self._break_outer_groups()
208 self._break_outer_groups()
209 else:
209 else:
210 self.output.write(obj)
210 self.output.write(obj)
211 self.output_width += width
211 self.output_width += width
212
212
213 def breakable(self, sep=' '):
213 def breakable(self, sep=' '):
214 """
214 """
215 Add a breakable separator to the output. This does not mean that it
215 Add a breakable separator to the output. This does not mean that it
216 will automatically break here. If no breaking on this position takes
216 will automatically break here. If no breaking on this position takes
217 place the `sep` is inserted which default to one space.
217 place the `sep` is inserted which default to one space.
218 """
218 """
219 width = len(sep)
219 width = len(sep)
220 group = self.group_stack[-1]
220 group = self.group_stack[-1]
221 if group.want_break:
221 if group.want_break:
222 self.flush()
222 self.flush()
223 self.output.write(self.newline)
223 self.output.write(self.newline)
224 self.output.write(' ' * self.indentation)
224 self.output.write(' ' * self.indentation)
225 self.output_width = self.indentation
225 self.output_width = self.indentation
226 self.buffer_width = 0
226 self.buffer_width = 0
227 else:
227 else:
228 self.buffer.append(Breakable(sep, width, self))
228 self.buffer.append(Breakable(sep, width, self))
229 self.buffer_width += width
229 self.buffer_width += width
230 self._break_outer_groups()
230 self._break_outer_groups()
231
231
232 def break_(self):
232 def break_(self):
233 """
233 """
234 Explicitly insert a newline into the output, maintaining correct indentation.
234 Explicitly insert a newline into the output, maintaining correct indentation.
235 """
235 """
236 self.flush()
236 self.flush()
237 self.output.write(self.newline)
237 self.output.write(self.newline)
238 self.output.write(' ' * self.indentation)
238 self.output.write(' ' * self.indentation)
239 self.output_width = self.indentation
239 self.output_width = self.indentation
240 self.buffer_width = 0
240 self.buffer_width = 0
241
241
242
242
243 def begin_group(self, indent=0, open=''):
243 def begin_group(self, indent=0, open=''):
244 """
244 """
245 Begin a group. If you want support for python < 2.5 which doesn't has
245 Begin a group. If you want support for python < 2.5 which doesn't has
246 the with statement this is the preferred way:
246 the with statement this is the preferred way:
247
247
248 p.begin_group(1, '{')
248 p.begin_group(1, '{')
249 ...
249 ...
250 p.end_group(1, '}')
250 p.end_group(1, '}')
251
251
252 The python 2.5 expression would be this:
252 The python 2.5 expression would be this:
253
253
254 with p.group(1, '{', '}'):
254 with p.group(1, '{', '}'):
255 ...
255 ...
256
256
257 The first parameter specifies the indentation for the next line (usually
257 The first parameter specifies the indentation for the next line (usually
258 the width of the opening text), the second the opening text. All
258 the width of the opening text), the second the opening text. All
259 parameters are optional.
259 parameters are optional.
260 """
260 """
261 if open:
261 if open:
262 self.text(open)
262 self.text(open)
263 group = Group(self.group_stack[-1].depth + 1)
263 group = Group(self.group_stack[-1].depth + 1)
264 self.group_stack.append(group)
264 self.group_stack.append(group)
265 self.group_queue.enq(group)
265 self.group_queue.enq(group)
266 self.indentation += indent
266 self.indentation += indent
267
267
268 def _enumerate(self, seq):
268 def _enumerate(self, seq):
269 """like enumerate, but with an upper limit on the number of items"""
269 """like enumerate, but with an upper limit on the number of items"""
270 for idx, x in enumerate(seq):
270 for idx, x in enumerate(seq):
271 if self.max_seq_length and idx >= self.max_seq_length:
271 if self.max_seq_length and idx >= self.max_seq_length:
272 self.text(',')
272 self.text(',')
273 self.breakable()
273 self.breakable()
274 self.text('...')
274 self.text('...')
275 return
275 return
276 yield idx, x
276 yield idx, x
277
277
278 def end_group(self, dedent=0, close=''):
278 def end_group(self, dedent=0, close=''):
279 """End a group. See `begin_group` for more details."""
279 """End a group. See `begin_group` for more details."""
280 self.indentation -= dedent
280 self.indentation -= dedent
281 group = self.group_stack.pop()
281 group = self.group_stack.pop()
282 if not group.breakables:
282 if not group.breakables:
283 self.group_queue.remove(group)
283 self.group_queue.remove(group)
284 if close:
284 if close:
285 self.text(close)
285 self.text(close)
286
286
287 def flush(self):
287 def flush(self):
288 """Flush data that is left in the buffer."""
288 """Flush data that is left in the buffer."""
289 for data in self.buffer:
289 for data in self.buffer:
290 self.output_width += data.output(self.output, self.output_width)
290 self.output_width += data.output(self.output, self.output_width)
291 self.buffer.clear()
291 self.buffer.clear()
292 self.buffer_width = 0
292 self.buffer_width = 0
293
293
294
294
295 def _get_mro(obj_class):
295 def _get_mro(obj_class):
296 """ Get a reasonable method resolution order of a class and its superclasses
296 """ Get a reasonable method resolution order of a class and its superclasses
297 for both old-style and new-style classes.
297 for both old-style and new-style classes.
298 """
298 """
299 if not hasattr(obj_class, '__mro__'):
299 if not hasattr(obj_class, '__mro__'):
300 # Old-style class. Mix in object to make a fake new-style class.
300 # Old-style class. Mix in object to make a fake new-style class.
301 try:
301 try:
302 obj_class = type(obj_class.__name__, (obj_class, object), {})
302 obj_class = type(obj_class.__name__, (obj_class, object), {})
303 except TypeError:
303 except TypeError:
304 # Old-style extension type that does not descend from object.
304 # Old-style extension type that does not descend from object.
305 # FIXME: try to construct a more thorough MRO.
305 # FIXME: try to construct a more thorough MRO.
306 mro = [obj_class]
306 mro = [obj_class]
307 else:
307 else:
308 mro = obj_class.__mro__[1:-1]
308 mro = obj_class.__mro__[1:-1]
309 else:
309 else:
310 mro = obj_class.__mro__
310 mro = obj_class.__mro__
311 return mro
311 return mro
312
312
313
313
314 class RepresentationPrinter(PrettyPrinter):
314 class RepresentationPrinter(PrettyPrinter):
315 """
315 """
316 Special pretty printer that has a `pretty` method that calls the pretty
316 Special pretty printer that has a `pretty` method that calls the pretty
317 printer for a python object.
317 printer for a python object.
318
318
319 This class stores processing data on `self` so you must *never* use
319 This class stores processing data on `self` so you must *never* use
320 this class in a threaded environment. Always lock it or reinstanciate
320 this class in a threaded environment. Always lock it or reinstanciate
321 it.
321 it.
322
322
323 Instances also have a verbose flag callbacks can access to control their
323 Instances also have a verbose flag callbacks can access to control their
324 output. For example the default instance repr prints all attributes and
324 output. For example the default instance repr prints all attributes and
325 methods that are not prefixed by an underscore if the printer is in
325 methods that are not prefixed by an underscore if the printer is in
326 verbose mode.
326 verbose mode.
327 """
327 """
328
328
329 def __init__(self, output, verbose=False, max_width=79, newline='\n',
329 def __init__(self, output, verbose=False, max_width=79, newline='\n',
330 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
330 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
331 max_seq_length=MAX_SEQ_LENGTH):
331 max_seq_length=MAX_SEQ_LENGTH):
332
332
333 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
333 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
334 self.verbose = verbose
334 self.verbose = verbose
335 self.stack = []
335 self.stack = []
336 if singleton_pprinters is None:
336 if singleton_pprinters is None:
337 singleton_pprinters = _singleton_pprinters.copy()
337 singleton_pprinters = _singleton_pprinters.copy()
338 self.singleton_pprinters = singleton_pprinters
338 self.singleton_pprinters = singleton_pprinters
339 if type_pprinters is None:
339 if type_pprinters is None:
340 type_pprinters = _type_pprinters.copy()
340 type_pprinters = _type_pprinters.copy()
341 self.type_pprinters = type_pprinters
341 self.type_pprinters = type_pprinters
342 if deferred_pprinters is None:
342 if deferred_pprinters is None:
343 deferred_pprinters = _deferred_type_pprinters.copy()
343 deferred_pprinters = _deferred_type_pprinters.copy()
344 self.deferred_pprinters = deferred_pprinters
344 self.deferred_pprinters = deferred_pprinters
345
345
346 def pretty(self, obj):
346 def pretty(self, obj):
347 """Pretty print the given object."""
347 """Pretty print the given object."""
348 obj_id = id(obj)
348 obj_id = id(obj)
349 cycle = obj_id in self.stack
349 cycle = obj_id in self.stack
350 self.stack.append(obj_id)
350 self.stack.append(obj_id)
351 self.begin_group()
351 self.begin_group()
352 try:
352 try:
353 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
353 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
354 # First try to find registered singleton printers for the type.
354 # First try to find registered singleton printers for the type.
355 try:
355 try:
356 printer = self.singleton_pprinters[obj_id]
356 printer = self.singleton_pprinters[obj_id]
357 except (TypeError, KeyError):
357 except (TypeError, KeyError):
358 pass
358 pass
359 else:
359 else:
360 return printer(obj, self, cycle)
360 return printer(obj, self, cycle)
361 # Next walk the mro and check for either:
361 # Next walk the mro and check for either:
362 # 1) a registered printer
362 # 1) a registered printer
363 # 2) a _repr_pretty_ method
363 # 2) a _repr_pretty_ method
364 for cls in _get_mro(obj_class):
364 for cls in _get_mro(obj_class):
365 if cls in self.type_pprinters:
365 if cls in self.type_pprinters:
366 # printer registered in self.type_pprinters
366 # printer registered in self.type_pprinters
367 return self.type_pprinters[cls](obj, self, cycle)
367 return self.type_pprinters[cls](obj, self, cycle)
368 else:
368 else:
369 # deferred printer
369 # deferred printer
370 printer = self._in_deferred_types(cls)
370 printer = self._in_deferred_types(cls)
371 if printer is not None:
371 if printer is not None:
372 return printer(obj, self, cycle)
372 return printer(obj, self, cycle)
373 else:
373 else:
374 # Finally look for special method names.
374 # Finally look for special method names.
375 # Some objects automatically create any requested
375 # Some objects automatically create any requested
376 # attribute. Try to ignore most of them by checking for
376 # attribute. Try to ignore most of them by checking for
377 # callability.
377 # callability.
378 if '_repr_pretty_' in cls.__dict__:
378 if '_repr_pretty_' in cls.__dict__:
379 meth = cls._repr_pretty_
379 meth = cls._repr_pretty_
380 if callable(meth):
380 if callable(meth):
381 return meth(obj, self, cycle)
381 return meth(obj, self, cycle)
382 return _default_pprint(obj, self, cycle)
382 return _default_pprint(obj, self, cycle)
383 finally:
383 finally:
384 self.end_group()
384 self.end_group()
385 self.stack.pop()
385 self.stack.pop()
386
386
387 def _in_deferred_types(self, cls):
387 def _in_deferred_types(self, cls):
388 """
388 """
389 Check if the given class is specified in the deferred type registry.
389 Check if the given class is specified in the deferred type registry.
390
390
391 Returns the printer from the registry if it exists, and None if the
391 Returns the printer from the registry if it exists, and None if the
392 class is not in the registry. Successful matches will be moved to the
392 class is not in the registry. Successful matches will be moved to the
393 regular type registry for future use.
393 regular type registry for future use.
394 """
394 """
395 mod = _safe_getattr(cls, '__module__', None)
395 mod = _safe_getattr(cls, '__module__', None)
396 name = _safe_getattr(cls, '__name__', None)
396 name = _safe_getattr(cls, '__name__', None)
397 key = (mod, name)
397 key = (mod, name)
398 printer = None
398 printer = None
399 if key in self.deferred_pprinters:
399 if key in self.deferred_pprinters:
400 # Move the printer over to the regular registry.
400 # Move the printer over to the regular registry.
401 printer = self.deferred_pprinters.pop(key)
401 printer = self.deferred_pprinters.pop(key)
402 self.type_pprinters[cls] = printer
402 self.type_pprinters[cls] = printer
403 return printer
403 return printer
404
404
405
405
406 class Printable(object):
406 class Printable(object):
407
407
408 def output(self, stream, output_width):
408 def output(self, stream, output_width):
409 return output_width
409 return output_width
410
410
411
411
412 class Text(Printable):
412 class Text(Printable):
413
413
414 def __init__(self):
414 def __init__(self):
415 self.objs = []
415 self.objs = []
416 self.width = 0
416 self.width = 0
417
417
418 def output(self, stream, output_width):
418 def output(self, stream, output_width):
419 for obj in self.objs:
419 for obj in self.objs:
420 stream.write(obj)
420 stream.write(obj)
421 return output_width + self.width
421 return output_width + self.width
422
422
423 def add(self, obj, width):
423 def add(self, obj, width):
424 self.objs.append(obj)
424 self.objs.append(obj)
425 self.width += width
425 self.width += width
426
426
427
427
428 class Breakable(Printable):
428 class Breakable(Printable):
429
429
430 def __init__(self, seq, width, pretty):
430 def __init__(self, seq, width, pretty):
431 self.obj = seq
431 self.obj = seq
432 self.width = width
432 self.width = width
433 self.pretty = pretty
433 self.pretty = pretty
434 self.indentation = pretty.indentation
434 self.indentation = pretty.indentation
435 self.group = pretty.group_stack[-1]
435 self.group = pretty.group_stack[-1]
436 self.group.breakables.append(self)
436 self.group.breakables.append(self)
437
437
438 def output(self, stream, output_width):
438 def output(self, stream, output_width):
439 self.group.breakables.popleft()
439 self.group.breakables.popleft()
440 if self.group.want_break:
440 if self.group.want_break:
441 stream.write(self.pretty.newline)
441 stream.write(self.pretty.newline)
442 stream.write(' ' * self.indentation)
442 stream.write(' ' * self.indentation)
443 return self.indentation
443 return self.indentation
444 if not self.group.breakables:
444 if not self.group.breakables:
445 self.pretty.group_queue.remove(self.group)
445 self.pretty.group_queue.remove(self.group)
446 stream.write(self.obj)
446 stream.write(self.obj)
447 return output_width + self.width
447 return output_width + self.width
448
448
449
449
450 class Group(Printable):
450 class Group(Printable):
451
451
452 def __init__(self, depth):
452 def __init__(self, depth):
453 self.depth = depth
453 self.depth = depth
454 self.breakables = deque()
454 self.breakables = deque()
455 self.want_break = False
455 self.want_break = False
456
456
457
457
458 class GroupQueue(object):
458 class GroupQueue(object):
459
459
460 def __init__(self, *groups):
460 def __init__(self, *groups):
461 self.queue = []
461 self.queue = []
462 for group in groups:
462 for group in groups:
463 self.enq(group)
463 self.enq(group)
464
464
465 def enq(self, group):
465 def enq(self, group):
466 depth = group.depth
466 depth = group.depth
467 while depth > len(self.queue) - 1:
467 while depth > len(self.queue) - 1:
468 self.queue.append([])
468 self.queue.append([])
469 self.queue[depth].append(group)
469 self.queue[depth].append(group)
470
470
471 def deq(self):
471 def deq(self):
472 for stack in self.queue:
472 for stack in self.queue:
473 for idx, group in enumerate(reversed(stack)):
473 for idx, group in enumerate(reversed(stack)):
474 if group.breakables:
474 if group.breakables:
475 del stack[idx]
475 del stack[idx]
476 group.want_break = True
476 group.want_break = True
477 return group
477 return group
478 for group in stack:
478 for group in stack:
479 group.want_break = True
479 group.want_break = True
480 del stack[:]
480 del stack[:]
481
481
482 def remove(self, group):
482 def remove(self, group):
483 try:
483 try:
484 self.queue[group.depth].remove(group)
484 self.queue[group.depth].remove(group)
485 except ValueError:
485 except ValueError:
486 pass
486 pass
487
487
488 try:
488 try:
489 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
489 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
490 except AttributeError: # Python 3
490 except AttributeError: # Python 3
491 _baseclass_reprs = (object.__repr__,)
491 _baseclass_reprs = (object.__repr__,)
492
492
493
493
494 def _default_pprint(obj, p, cycle):
494 def _default_pprint(obj, p, cycle):
495 """
495 """
496 The default print function. Used if an object does not provide one and
496 The default print function. Used if an object does not provide one and
497 it's none of the builtin objects.
497 it's none of the builtin objects.
498 """
498 """
499 klass = _safe_getattr(obj, '__class__', None) or type(obj)
499 klass = _safe_getattr(obj, '__class__', None) or type(obj)
500 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
500 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
501 # A user-provided repr. Find newlines and replace them with p.break_()
501 # A user-provided repr. Find newlines and replace them with p.break_()
502 _repr_pprint(obj, p, cycle)
502 _repr_pprint(obj, p, cycle)
503 return
503 return
504 p.begin_group(1, '<')
504 p.begin_group(1, '<')
505 p.pretty(klass)
505 p.pretty(klass)
506 p.text(' at 0x%x' % id(obj))
506 p.text(' at 0x%x' % id(obj))
507 if cycle:
507 if cycle:
508 p.text(' ...')
508 p.text(' ...')
509 elif p.verbose:
509 elif p.verbose:
510 first = True
510 first = True
511 for key in dir(obj):
511 for key in dir(obj):
512 if not key.startswith('_'):
512 if not key.startswith('_'):
513 try:
513 try:
514 value = getattr(obj, key)
514 value = getattr(obj, key)
515 except AttributeError:
515 except AttributeError:
516 continue
516 continue
517 if isinstance(value, types.MethodType):
517 if isinstance(value, types.MethodType):
518 continue
518 continue
519 if not first:
519 if not first:
520 p.text(',')
520 p.text(',')
521 p.breakable()
521 p.breakable()
522 p.text(key)
522 p.text(key)
523 p.text('=')
523 p.text('=')
524 step = len(key) + 1
524 step = len(key) + 1
525 p.indentation += step
525 p.indentation += step
526 p.pretty(value)
526 p.pretty(value)
527 p.indentation -= step
527 p.indentation -= step
528 first = False
528 first = False
529 p.end_group(1, '>')
529 p.end_group(1, '>')
530
530
531
531
532 def _seq_pprinter_factory(start, end, basetype):
532 def _seq_pprinter_factory(start, end, basetype):
533 """
533 """
534 Factory that returns a pprint function useful for sequences. Used by
534 Factory that returns a pprint function useful for sequences. Used by
535 the default pprint for tuples, dicts, and lists.
535 the default pprint for tuples, dicts, and lists.
536 """
536 """
537 def inner(obj, p, cycle):
537 def inner(obj, p, cycle):
538 typ = type(obj)
538 typ = type(obj)
539 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
539 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
540 # If the subclass provides its own repr, use it instead.
540 # If the subclass provides its own repr, use it instead.
541 return p.text(typ.__repr__(obj))
541 return p.text(typ.__repr__(obj))
542
542
543 if cycle:
543 if cycle:
544 return p.text(start + '...' + end)
544 return p.text(start + '...' + end)
545 step = len(start)
545 step = len(start)
546 p.begin_group(step, start)
546 p.begin_group(step, start)
547 for idx, x in p._enumerate(obj):
547 for idx, x in p._enumerate(obj):
548 if idx:
548 if idx:
549 p.text(',')
549 p.text(',')
550 p.breakable()
550 p.breakable()
551 p.pretty(x)
551 p.pretty(x)
552 if len(obj) == 1 and type(obj) is tuple:
552 if len(obj) == 1 and type(obj) is tuple:
553 # Special case for 1-item tuples.
553 # Special case for 1-item tuples.
554 p.text(',')
554 p.text(',')
555 p.end_group(step, end)
555 p.end_group(step, end)
556 return inner
556 return inner
557
557
558
558
559 def _set_pprinter_factory(start, end, basetype):
559 def _set_pprinter_factory(start, end, basetype):
560 """
560 """
561 Factory that returns a pprint function useful for sets and frozensets.
561 Factory that returns a pprint function useful for sets and frozensets.
562 """
562 """
563 def inner(obj, p, cycle):
563 def inner(obj, p, cycle):
564 typ = type(obj)
564 typ = type(obj)
565 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
565 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
566 # If the subclass provides its own repr, use it instead.
566 # If the subclass provides its own repr, use it instead.
567 return p.text(typ.__repr__(obj))
567 return p.text(typ.__repr__(obj))
568
568
569 if cycle:
569 if cycle:
570 return p.text(start + '...' + end)
570 return p.text(start + '...' + end)
571 if len(obj) == 0:
571 if len(obj) == 0:
572 # Special case.
572 # Special case.
573 p.text(basetype.__name__ + '()')
573 p.text(basetype.__name__ + '()')
574 else:
574 else:
575 step = len(start)
575 step = len(start)
576 p.begin_group(step, start)
576 p.begin_group(step, start)
577 # Like dictionary keys, we will try to sort the items if there aren't too many
577 # Like dictionary keys, we will try to sort the items if there aren't too many
578 items = obj
578 items = obj
579 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
579 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
580 try:
580 try:
581 items = sorted(obj)
581 items = sorted(obj)
582 except Exception:
582 except Exception:
583 # Sometimes the items don't sort.
583 # Sometimes the items don't sort.
584 pass
584 pass
585 for idx, x in p._enumerate(items):
585 for idx, x in p._enumerate(items):
586 if idx:
586 if idx:
587 p.text(',')
587 p.text(',')
588 p.breakable()
588 p.breakable()
589 p.pretty(x)
589 p.pretty(x)
590 p.end_group(step, end)
590 p.end_group(step, end)
591 return inner
591 return inner
592
592
593
593
594 def _dict_pprinter_factory(start, end, basetype=None):
594 def _dict_pprinter_factory(start, end, basetype=None):
595 """
595 """
596 Factory that returns a pprint function used by the default pprint of
596 Factory that returns a pprint function used by the default pprint of
597 dicts and dict proxies.
597 dicts and dict proxies.
598 """
598 """
599 def inner(obj, p, cycle):
599 def inner(obj, p, cycle):
600 typ = type(obj)
600 typ = type(obj)
601 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
601 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
602 # If the subclass provides its own repr, use it instead.
602 # If the subclass provides its own repr, use it instead.
603 return p.text(typ.__repr__(obj))
603 return p.text(typ.__repr__(obj))
604
604
605 if cycle:
605 if cycle:
606 return p.text('{...}')
606 return p.text('{...}')
607 step = len(start)
607 step = len(start)
608 p.begin_group(step, start)
608 p.begin_group(step, start)
609 keys = obj.keys()
609 keys = obj.keys()
610 # if dict isn't large enough to be truncated, sort keys before displaying
610 # if dict isn't large enough to be truncated, sort keys before displaying
611 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
611 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
612 try:
612 try:
613 keys = sorted(keys)
613 keys = sorted(keys)
614 except Exception:
614 except Exception:
615 # Sometimes the keys don't sort.
615 # Sometimes the keys don't sort.
616 pass
616 pass
617 for idx, key in p._enumerate(keys):
617 for idx, key in p._enumerate(keys):
618 if idx:
618 if idx:
619 p.text(',')
619 p.text(',')
620 p.breakable()
620 p.breakable()
621 p.pretty(key)
621 p.pretty(key)
622 p.text(': ')
622 p.text(': ')
623 p.pretty(obj[key])
623 p.pretty(obj[key])
624 p.end_group(step, end)
624 p.end_group(step, end)
625 return inner
625 return inner
626
626
627
627
628 def _super_pprint(obj, p, cycle):
628 def _super_pprint(obj, p, cycle):
629 """The pprint for the super type."""
629 """The pprint for the super type."""
630 p.begin_group(8, '<super: ')
630 p.begin_group(8, '<super: ')
631 p.pretty(obj.__thisclass__)
631 p.pretty(obj.__thisclass__)
632 p.text(',')
632 p.text(',')
633 p.breakable()
633 p.breakable()
634 if PYPY: # In PyPy, super() objects don't have __self__ attributes
634 if PYPY: # In PyPy, super() objects don't have __self__ attributes
635 dself = obj.__repr__.__self__
635 dself = obj.__repr__.__self__
636 p.pretty(None if dself is obj else dself)
636 p.pretty(None if dself is obj else dself)
637 else:
637 else:
638 p.pretty(obj.__self__)
638 p.pretty(obj.__self__)
639 p.end_group(8, '>')
639 p.end_group(8, '>')
640
640
641
641
642 def _re_pattern_pprint(obj, p, cycle):
642 def _re_pattern_pprint(obj, p, cycle):
643 """The pprint function for regular expression patterns."""
643 """The pprint function for regular expression patterns."""
644 p.text('re.compile(')
644 p.text('re.compile(')
645 pattern = repr(obj.pattern)
645 pattern = repr(obj.pattern)
646 if pattern[:1] in 'uU':
646 if pattern[:1] in 'uU':
647 pattern = pattern[1:]
647 pattern = pattern[1:]
648 prefix = 'ur'
648 prefix = 'ur'
649 else:
649 else:
650 prefix = 'r'
650 prefix = 'r'
651 pattern = prefix + pattern.replace('\\\\', '\\')
651 pattern = prefix + pattern.replace('\\\\', '\\')
652 p.text(pattern)
652 p.text(pattern)
653 if obj.flags:
653 if obj.flags:
654 p.text(',')
654 p.text(',')
655 p.breakable()
655 p.breakable()
656 done_one = False
656 done_one = False
657 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
657 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
658 'UNICODE', 'VERBOSE', 'DEBUG'):
658 'UNICODE', 'VERBOSE', 'DEBUG'):
659 if obj.flags & getattr(re, flag):
659 if obj.flags & getattr(re, flag):
660 if done_one:
660 if done_one:
661 p.text('|')
661 p.text('|')
662 p.text('re.' + flag)
662 p.text('re.' + flag)
663 done_one = True
663 done_one = True
664 p.text(')')
664 p.text(')')
665
665
666
666
667 def _type_pprint(obj, p, cycle):
667 def _type_pprint(obj, p, cycle):
668 """The pprint for classes and types."""
668 """The pprint for classes and types."""
669 # Heap allocated types might not have the module attribute,
669 # Heap allocated types might not have the module attribute,
670 # and others may set it to None.
670 # and others may set it to None.
671
671
672 # Checks for a __repr__ override in the metaclass. Can't compare the
672 # Checks for a __repr__ override in the metaclass. Can't compare the
673 # type(obj).__repr__ directly because in PyPy the representation function
673 # type(obj).__repr__ directly because in PyPy the representation function
674 # inherited from type isn't the same type.__repr__
674 # inherited from type isn't the same type.__repr__
675 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
675 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
676 _repr_pprint(obj, p, cycle)
676 _repr_pprint(obj, p, cycle)
677 return
677 return
678
678
679 mod = _safe_getattr(obj, '__module__', None)
679 mod = _safe_getattr(obj, '__module__', None)
680 try:
680 try:
681 name = obj.__qualname__
681 name = obj.__qualname__
682 if not isinstance(name, string_types):
682 if not isinstance(name, string_types):
683 # This can happen if the type implements __qualname__ as a property
683 # This can happen if the type implements __qualname__ as a property
684 # or other descriptor in Python 2.
684 # or other descriptor in Python 2.
685 raise Exception("Try __name__")
685 raise Exception("Try __name__")
686 except Exception:
686 except Exception:
687 name = obj.__name__
687 name = obj.__name__
688 if not isinstance(name, string_types):
688 if not isinstance(name, string_types):
689 name = '<unknown type>'
689 name = '<unknown type>'
690
690
691 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
691 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
692 p.text(name)
692 p.text(name)
693 else:
693 else:
694 p.text(mod + '.' + name)
694 p.text(mod + '.' + name)
695
695
696
696
697 def _repr_pprint(obj, p, cycle):
697 def _repr_pprint(obj, p, cycle):
698 """A pprint that just redirects to the normal repr function."""
698 """A pprint that just redirects to the normal repr function."""
699 # Find newlines and replace them with p.break_()
699 # Find newlines and replace them with p.break_()
700 output = repr(obj)
700 output = repr(obj)
701 for idx,output_line in enumerate(output.splitlines()):
701 for idx,output_line in enumerate(output.splitlines()):
702 if idx:
702 if idx:
703 p.break_()
703 p.break_()
704 p.text(output_line)
704 p.text(output_line)
705
705
706
706
707 def _function_pprint(obj, p, cycle):
707 def _function_pprint(obj, p, cycle):
708 """Base pprint for all functions and builtin functions."""
708 """Base pprint for all functions and builtin functions."""
709 name = _safe_getattr(obj, '__qualname__', obj.__name__)
709 name = _safe_getattr(obj, '__qualname__', obj.__name__)
710 mod = obj.__module__
710 mod = obj.__module__
711 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
711 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
712 name = mod + '.' + name
712 name = mod + '.' + name
713 p.text('<function %s>' % name)
713 p.text('<function %s>' % name)
714
714
715
715
716 def _exception_pprint(obj, p, cycle):
716 def _exception_pprint(obj, p, cycle):
717 """Base pprint for all exceptions."""
717 """Base pprint for all exceptions."""
718 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
718 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
719 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
719 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
720 name = '%s.%s' % (obj.__class__.__module__, name)
720 name = '%s.%s' % (obj.__class__.__module__, name)
721 step = len(name) + 1
721 step = len(name) + 1
722 p.begin_group(step, name + '(')
722 p.begin_group(step, name + '(')
723 for idx, arg in enumerate(getattr(obj, 'args', ())):
723 for idx, arg in enumerate(getattr(obj, 'args', ())):
724 if idx:
724 if idx:
725 p.text(',')
725 p.text(',')
726 p.breakable()
726 p.breakable()
727 p.pretty(arg)
727 p.pretty(arg)
728 p.end_group(step, ')')
728 p.end_group(step, ')')
729
729
730
730
731 #: the exception base
731 #: the exception base
732 try:
732 try:
733 _exception_base = BaseException
733 _exception_base = BaseException
734 except NameError:
734 except NameError:
735 _exception_base = Exception
735 _exception_base = Exception
736
736
737
737
738 #: printers for builtin types
738 #: printers for builtin types
739 _type_pprinters = {
739 _type_pprinters = {
740 int: _repr_pprint,
740 int: _repr_pprint,
741 float: _repr_pprint,
741 float: _repr_pprint,
742 str: _repr_pprint,
742 str: _repr_pprint,
743 tuple: _seq_pprinter_factory('(', ')', tuple),
743 tuple: _seq_pprinter_factory('(', ')', tuple),
744 list: _seq_pprinter_factory('[', ']', list),
744 list: _seq_pprinter_factory('[', ']', list),
745 dict: _dict_pprinter_factory('{', '}', dict),
745 dict: _dict_pprinter_factory('{', '}', dict),
746
746
747 set: _set_pprinter_factory('{', '}', set),
747 set: _set_pprinter_factory('{', '}', set),
748 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
748 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
749 super: _super_pprint,
749 super: _super_pprint,
750 _re_pattern_type: _re_pattern_pprint,
750 _re_pattern_type: _re_pattern_pprint,
751 type: _type_pprint,
751 type: _type_pprint,
752 types.FunctionType: _function_pprint,
752 types.FunctionType: _function_pprint,
753 types.BuiltinFunctionType: _function_pprint,
753 types.BuiltinFunctionType: _function_pprint,
754 types.MethodType: _repr_pprint,
754 types.MethodType: _repr_pprint,
755
755
756 datetime.datetime: _repr_pprint,
756 datetime.datetime: _repr_pprint,
757 datetime.timedelta: _repr_pprint,
757 datetime.timedelta: _repr_pprint,
758 _exception_base: _exception_pprint
758 _exception_base: _exception_pprint
759 }
759 }
760
760
761 try:
761 try:
762 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
762 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
763 # using dict.setdefault avoids overwritting the dict printer
763 # using dict.setdefault avoids overwritting the dict printer
764 _type_pprinters.setdefault(types.DictProxyType,
764 _type_pprinters.setdefault(types.DictProxyType,
765 _dict_pprinter_factory('dict_proxy({', '})'))
765 _dict_pprinter_factory('dict_proxy({', '})'))
766 _type_pprinters[types.ClassType] = _type_pprint
766 _type_pprinters[types.ClassType] = _type_pprint
767 _type_pprinters[types.SliceType] = _repr_pprint
767 _type_pprinters[types.SliceType] = _repr_pprint
768 except AttributeError: # Python 3
768 except AttributeError: # Python 3
769 _type_pprinters[types.MappingProxyType] = \
769 _type_pprinters[types.MappingProxyType] = \
770 _dict_pprinter_factory('mappingproxy({', '})')
770 _dict_pprinter_factory('mappingproxy({', '})')
771 _type_pprinters[slice] = _repr_pprint
771 _type_pprinters[slice] = _repr_pprint
772
772
773 try:
773 try:
774 _type_pprinters[xrange] = _repr_pprint
775 _type_pprinters[long] = _repr_pprint
774 _type_pprinters[long] = _repr_pprint
776 _type_pprinters[unicode] = _repr_pprint
775 _type_pprinters[unicode] = _repr_pprint
777 except NameError:
776 except NameError:
778 _type_pprinters[range] = _repr_pprint
777 _type_pprinters[range] = _repr_pprint
779 _type_pprinters[bytes] = _repr_pprint
778 _type_pprinters[bytes] = _repr_pprint
780
779
781 #: printers for types specified by name
780 #: printers for types specified by name
782 _deferred_type_pprinters = {
781 _deferred_type_pprinters = {
783 }
782 }
784
783
785 def for_type(typ, func):
784 def for_type(typ, func):
786 """
785 """
787 Add a pretty printer for a given type.
786 Add a pretty printer for a given type.
788 """
787 """
789 oldfunc = _type_pprinters.get(typ, None)
788 oldfunc = _type_pprinters.get(typ, None)
790 if func is not None:
789 if func is not None:
791 # To support easy restoration of old pprinters, we need to ignore Nones.
790 # To support easy restoration of old pprinters, we need to ignore Nones.
792 _type_pprinters[typ] = func
791 _type_pprinters[typ] = func
793 return oldfunc
792 return oldfunc
794
793
795 def for_type_by_name(type_module, type_name, func):
794 def for_type_by_name(type_module, type_name, func):
796 """
795 """
797 Add a pretty printer for a type specified by the module and name of a type
796 Add a pretty printer for a type specified by the module and name of a type
798 rather than the type object itself.
797 rather than the type object itself.
799 """
798 """
800 key = (type_module, type_name)
799 key = (type_module, type_name)
801 oldfunc = _deferred_type_pprinters.get(key, None)
800 oldfunc = _deferred_type_pprinters.get(key, None)
802 if func is not None:
801 if func is not None:
803 # To support easy restoration of old pprinters, we need to ignore Nones.
802 # To support easy restoration of old pprinters, we need to ignore Nones.
804 _deferred_type_pprinters[key] = func
803 _deferred_type_pprinters[key] = func
805 return oldfunc
804 return oldfunc
806
805
807
806
808 #: printers for the default singletons
807 #: printers for the default singletons
809 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
808 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
810 NotImplemented]), _repr_pprint)
809 NotImplemented]), _repr_pprint)
811
810
812
811
813 def _defaultdict_pprint(obj, p, cycle):
812 def _defaultdict_pprint(obj, p, cycle):
814 name = obj.__class__.__name__
813 name = obj.__class__.__name__
815 with p.group(len(name) + 1, name + '(', ')'):
814 with p.group(len(name) + 1, name + '(', ')'):
816 if cycle:
815 if cycle:
817 p.text('...')
816 p.text('...')
818 else:
817 else:
819 p.pretty(obj.default_factory)
818 p.pretty(obj.default_factory)
820 p.text(',')
819 p.text(',')
821 p.breakable()
820 p.breakable()
822 p.pretty(dict(obj))
821 p.pretty(dict(obj))
823
822
824 def _ordereddict_pprint(obj, p, cycle):
823 def _ordereddict_pprint(obj, p, cycle):
825 name = obj.__class__.__name__
824 name = obj.__class__.__name__
826 with p.group(len(name) + 1, name + '(', ')'):
825 with p.group(len(name) + 1, name + '(', ')'):
827 if cycle:
826 if cycle:
828 p.text('...')
827 p.text('...')
829 elif len(obj):
828 elif len(obj):
830 p.pretty(list(obj.items()))
829 p.pretty(list(obj.items()))
831
830
832 def _deque_pprint(obj, p, cycle):
831 def _deque_pprint(obj, p, cycle):
833 name = obj.__class__.__name__
832 name = obj.__class__.__name__
834 with p.group(len(name) + 1, name + '(', ')'):
833 with p.group(len(name) + 1, name + '(', ')'):
835 if cycle:
834 if cycle:
836 p.text('...')
835 p.text('...')
837 else:
836 else:
838 p.pretty(list(obj))
837 p.pretty(list(obj))
839
838
840
839
841 def _counter_pprint(obj, p, cycle):
840 def _counter_pprint(obj, p, cycle):
842 name = obj.__class__.__name__
841 name = obj.__class__.__name__
843 with p.group(len(name) + 1, name + '(', ')'):
842 with p.group(len(name) + 1, name + '(', ')'):
844 if cycle:
843 if cycle:
845 p.text('...')
844 p.text('...')
846 elif len(obj):
845 elif len(obj):
847 p.pretty(dict(obj))
846 p.pretty(dict(obj))
848
847
849 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
848 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
850 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
849 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
851 for_type_by_name('collections', 'deque', _deque_pprint)
850 for_type_by_name('collections', 'deque', _deque_pprint)
852 for_type_by_name('collections', 'Counter', _counter_pprint)
851 for_type_by_name('collections', 'Counter', _counter_pprint)
853
852
854 if __name__ == '__main__':
853 if __name__ == '__main__':
855 from random import randrange
854 from random import randrange
856 class Foo(object):
855 class Foo(object):
857 def __init__(self):
856 def __init__(self):
858 self.foo = 1
857 self.foo = 1
859 self.bar = re.compile(r'\s+')
858 self.bar = re.compile(r'\s+')
860 self.blub = dict.fromkeys(range(30), randrange(1, 40))
859 self.blub = dict.fromkeys(range(30), randrange(1, 40))
861 self.hehe = 23424.234234
860 self.hehe = 23424.234234
862 self.list = ["blub", "blah", self]
861 self.list = ["blub", "blah", self]
863
862
864 def get_foo(self):
863 def get_foo(self):
865 print("foo")
864 print("foo")
866
865
867 pprint(Foo(), verbose=True)
866 pprint(Foo(), verbose=True)
@@ -1,37 +1,36 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Utilities for working with data structures like lists, dicts and tuples.
2 """Utilities for working with data structures like lists, dicts and tuples.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2008-2011 The IPython Development Team
6 # Copyright (C) 2008-2011 The IPython Development Team
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 from .py3compat import xrange
13
12
14 def uniq_stable(elems):
13 def uniq_stable(elems):
15 """uniq_stable(elems) -> list
14 """uniq_stable(elems) -> list
16
15
17 Return from an iterable, a list of all the unique elements in the input,
16 Return from an iterable, a list of all the unique elements in the input,
18 but maintaining the order in which they first appear.
17 but maintaining the order in which they first appear.
19
18
20 Note: All elements in the input must be hashable for this routine
19 Note: All elements in the input must be hashable for this routine
21 to work, as it internally uses a set for efficiency reasons.
20 to work, as it internally uses a set for efficiency reasons.
22 """
21 """
23 seen = set()
22 seen = set()
24 return [x for x in elems if x not in seen and not seen.add(x)]
23 return [x for x in elems if x not in seen and not seen.add(x)]
25
24
26
25
27 def flatten(seq):
26 def flatten(seq):
28 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
27 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
29
28
30 return [x for subseq in seq for x in subseq]
29 return [x for subseq in seq for x in subseq]
31
30
32
31
33 def chop(seq, size):
32 def chop(seq, size):
34 """Chop a sequence into chunks of the given size."""
33 """Chop a sequence into chunks of the given size."""
35 return [seq[i:i+size] for i in xrange(0,len(seq),size)]
34 return [seq[i:i+size] for i in range(0,len(seq),size)]
36
35
37
36
@@ -1,774 +1,774 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with strings and text.
3 Utilities for working with strings and text.
4
4
5 Inheritance diagram:
5 Inheritance diagram:
6
6
7 .. inheritance-diagram:: IPython.utils.text
7 .. inheritance-diagram:: IPython.utils.text
8 :parts: 3
8 :parts: 3
9 """
9 """
10
10
11 import os
11 import os
12 import re
12 import re
13 import sys
13 import sys
14 import textwrap
14 import textwrap
15 from string import Formatter
15 from string import Formatter
16 try:
16 try:
17 from pathlib import Path
17 from pathlib import Path
18 except ImportError:
18 except ImportError:
19 # Python 2 backport
19 # Python 2 backport
20 from pathlib2 import Path
20 from pathlib2 import Path
21
21
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23
24 # datetime.strftime date format for ipython
24 # datetime.strftime date format for ipython
25 if sys.platform == 'win32':
25 if sys.platform == 'win32':
26 date_format = "%B %d, %Y"
26 date_format = "%B %d, %Y"
27 else:
27 else:
28 date_format = "%B %-d, %Y"
28 date_format = "%B %-d, %Y"
29
29
30 class LSString(str):
30 class LSString(str):
31 """String derivative with a special access attributes.
31 """String derivative with a special access attributes.
32
32
33 These are normal strings, but with the special attributes:
33 These are normal strings, but with the special attributes:
34
34
35 .l (or .list) : value as list (split on newlines).
35 .l (or .list) : value as list (split on newlines).
36 .n (or .nlstr): original value (the string itself).
36 .n (or .nlstr): original value (the string itself).
37 .s (or .spstr): value as whitespace-separated string.
37 .s (or .spstr): value as whitespace-separated string.
38 .p (or .paths): list of path objects (requires path.py package)
38 .p (or .paths): list of path objects (requires path.py package)
39
39
40 Any values which require transformations are computed only once and
40 Any values which require transformations are computed only once and
41 cached.
41 cached.
42
42
43 Such strings are very useful to efficiently interact with the shell, which
43 Such strings are very useful to efficiently interact with the shell, which
44 typically only understands whitespace-separated options for commands."""
44 typically only understands whitespace-separated options for commands."""
45
45
46 def get_list(self):
46 def get_list(self):
47 try:
47 try:
48 return self.__list
48 return self.__list
49 except AttributeError:
49 except AttributeError:
50 self.__list = self.split('\n')
50 self.__list = self.split('\n')
51 return self.__list
51 return self.__list
52
52
53 l = list = property(get_list)
53 l = list = property(get_list)
54
54
55 def get_spstr(self):
55 def get_spstr(self):
56 try:
56 try:
57 return self.__spstr
57 return self.__spstr
58 except AttributeError:
58 except AttributeError:
59 self.__spstr = self.replace('\n',' ')
59 self.__spstr = self.replace('\n',' ')
60 return self.__spstr
60 return self.__spstr
61
61
62 s = spstr = property(get_spstr)
62 s = spstr = property(get_spstr)
63
63
64 def get_nlstr(self):
64 def get_nlstr(self):
65 return self
65 return self
66
66
67 n = nlstr = property(get_nlstr)
67 n = nlstr = property(get_nlstr)
68
68
69 def get_paths(self):
69 def get_paths(self):
70 try:
70 try:
71 return self.__paths
71 return self.__paths
72 except AttributeError:
72 except AttributeError:
73 self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
73 self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
74 return self.__paths
74 return self.__paths
75
75
76 p = paths = property(get_paths)
76 p = paths = property(get_paths)
77
77
78 # FIXME: We need to reimplement type specific displayhook and then add this
78 # FIXME: We need to reimplement type specific displayhook and then add this
79 # back as a custom printer. This should also be moved outside utils into the
79 # back as a custom printer. This should also be moved outside utils into the
80 # core.
80 # core.
81
81
82 # def print_lsstring(arg):
82 # def print_lsstring(arg):
83 # """ Prettier (non-repr-like) and more informative printer for LSString """
83 # """ Prettier (non-repr-like) and more informative printer for LSString """
84 # print "LSString (.p, .n, .l, .s available). Value:"
84 # print "LSString (.p, .n, .l, .s available). Value:"
85 # print arg
85 # print arg
86 #
86 #
87 #
87 #
88 # print_lsstring = result_display.when_type(LSString)(print_lsstring)
88 # print_lsstring = result_display.when_type(LSString)(print_lsstring)
89
89
90
90
91 class SList(list):
91 class SList(list):
92 """List derivative with a special access attributes.
92 """List derivative with a special access attributes.
93
93
94 These are normal lists, but with the special attributes:
94 These are normal lists, but with the special attributes:
95
95
96 * .l (or .list) : value as list (the list itself).
96 * .l (or .list) : value as list (the list itself).
97 * .n (or .nlstr): value as a string, joined on newlines.
97 * .n (or .nlstr): value as a string, joined on newlines.
98 * .s (or .spstr): value as a string, joined on spaces.
98 * .s (or .spstr): value as a string, joined on spaces.
99 * .p (or .paths): list of path objects (requires path.py package)
99 * .p (or .paths): list of path objects (requires path.py package)
100
100
101 Any values which require transformations are computed only once and
101 Any values which require transformations are computed only once and
102 cached."""
102 cached."""
103
103
104 def get_list(self):
104 def get_list(self):
105 return self
105 return self
106
106
107 l = list = property(get_list)
107 l = list = property(get_list)
108
108
109 def get_spstr(self):
109 def get_spstr(self):
110 try:
110 try:
111 return self.__spstr
111 return self.__spstr
112 except AttributeError:
112 except AttributeError:
113 self.__spstr = ' '.join(self)
113 self.__spstr = ' '.join(self)
114 return self.__spstr
114 return self.__spstr
115
115
116 s = spstr = property(get_spstr)
116 s = spstr = property(get_spstr)
117
117
118 def get_nlstr(self):
118 def get_nlstr(self):
119 try:
119 try:
120 return self.__nlstr
120 return self.__nlstr
121 except AttributeError:
121 except AttributeError:
122 self.__nlstr = '\n'.join(self)
122 self.__nlstr = '\n'.join(self)
123 return self.__nlstr
123 return self.__nlstr
124
124
125 n = nlstr = property(get_nlstr)
125 n = nlstr = property(get_nlstr)
126
126
127 def get_paths(self):
127 def get_paths(self):
128 try:
128 try:
129 return self.__paths
129 return self.__paths
130 except AttributeError:
130 except AttributeError:
131 self.__paths = [Path(p) for p in self if os.path.exists(p)]
131 self.__paths = [Path(p) for p in self if os.path.exists(p)]
132 return self.__paths
132 return self.__paths
133
133
134 p = paths = property(get_paths)
134 p = paths = property(get_paths)
135
135
136 def grep(self, pattern, prune = False, field = None):
136 def grep(self, pattern, prune = False, field = None):
137 """ Return all strings matching 'pattern' (a regex or callable)
137 """ Return all strings matching 'pattern' (a regex or callable)
138
138
139 This is case-insensitive. If prune is true, return all items
139 This is case-insensitive. If prune is true, return all items
140 NOT matching the pattern.
140 NOT matching the pattern.
141
141
142 If field is specified, the match must occur in the specified
142 If field is specified, the match must occur in the specified
143 whitespace-separated field.
143 whitespace-separated field.
144
144
145 Examples::
145 Examples::
146
146
147 a.grep( lambda x: x.startswith('C') )
147 a.grep( lambda x: x.startswith('C') )
148 a.grep('Cha.*log', prune=1)
148 a.grep('Cha.*log', prune=1)
149 a.grep('chm', field=-1)
149 a.grep('chm', field=-1)
150 """
150 """
151
151
152 def match_target(s):
152 def match_target(s):
153 if field is None:
153 if field is None:
154 return s
154 return s
155 parts = s.split()
155 parts = s.split()
156 try:
156 try:
157 tgt = parts[field]
157 tgt = parts[field]
158 return tgt
158 return tgt
159 except IndexError:
159 except IndexError:
160 return ""
160 return ""
161
161
162 if isinstance(pattern, py3compat.string_types):
162 if isinstance(pattern, py3compat.string_types):
163 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
163 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
164 else:
164 else:
165 pred = pattern
165 pred = pattern
166 if not prune:
166 if not prune:
167 return SList([el for el in self if pred(match_target(el))])
167 return SList([el for el in self if pred(match_target(el))])
168 else:
168 else:
169 return SList([el for el in self if not pred(match_target(el))])
169 return SList([el for el in self if not pred(match_target(el))])
170
170
171 def fields(self, *fields):
171 def fields(self, *fields):
172 """ Collect whitespace-separated fields from string list
172 """ Collect whitespace-separated fields from string list
173
173
174 Allows quick awk-like usage of string lists.
174 Allows quick awk-like usage of string lists.
175
175
176 Example data (in var a, created by 'a = !ls -l')::
176 Example data (in var a, created by 'a = !ls -l')::
177
177
178 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
178 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
179 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
179 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
180
180
181 * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']``
181 * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']``
182 * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']``
182 * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']``
183 (note the joining by space).
183 (note the joining by space).
184 * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']``
184 * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']``
185
185
186 IndexErrors are ignored.
186 IndexErrors are ignored.
187
187
188 Without args, fields() just split()'s the strings.
188 Without args, fields() just split()'s the strings.
189 """
189 """
190 if len(fields) == 0:
190 if len(fields) == 0:
191 return [el.split() for el in self]
191 return [el.split() for el in self]
192
192
193 res = SList()
193 res = SList()
194 for el in [f.split() for f in self]:
194 for el in [f.split() for f in self]:
195 lineparts = []
195 lineparts = []
196
196
197 for fd in fields:
197 for fd in fields:
198 try:
198 try:
199 lineparts.append(el[fd])
199 lineparts.append(el[fd])
200 except IndexError:
200 except IndexError:
201 pass
201 pass
202 if lineparts:
202 if lineparts:
203 res.append(" ".join(lineparts))
203 res.append(" ".join(lineparts))
204
204
205 return res
205 return res
206
206
207 def sort(self,field= None, nums = False):
207 def sort(self,field= None, nums = False):
208 """ sort by specified fields (see fields())
208 """ sort by specified fields (see fields())
209
209
210 Example::
210 Example::
211
211
212 a.sort(1, nums = True)
212 a.sort(1, nums = True)
213
213
214 Sorts a by second field, in numerical order (so that 21 > 3)
214 Sorts a by second field, in numerical order (so that 21 > 3)
215
215
216 """
216 """
217
217
218 #decorate, sort, undecorate
218 #decorate, sort, undecorate
219 if field is not None:
219 if field is not None:
220 dsu = [[SList([line]).fields(field), line] for line in self]
220 dsu = [[SList([line]).fields(field), line] for line in self]
221 else:
221 else:
222 dsu = [[line, line] for line in self]
222 dsu = [[line, line] for line in self]
223 if nums:
223 if nums:
224 for i in range(len(dsu)):
224 for i in range(len(dsu)):
225 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
225 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
226 try:
226 try:
227 n = int(numstr)
227 n = int(numstr)
228 except ValueError:
228 except ValueError:
229 n = 0
229 n = 0
230 dsu[i][0] = n
230 dsu[i][0] = n
231
231
232
232
233 dsu.sort()
233 dsu.sort()
234 return SList([t[1] for t in dsu])
234 return SList([t[1] for t in dsu])
235
235
236
236
237 # FIXME: We need to reimplement type specific displayhook and then add this
237 # FIXME: We need to reimplement type specific displayhook and then add this
238 # back as a custom printer. This should also be moved outside utils into the
238 # back as a custom printer. This should also be moved outside utils into the
239 # core.
239 # core.
240
240
241 # def print_slist(arg):
241 # def print_slist(arg):
242 # """ Prettier (non-repr-like) and more informative printer for SList """
242 # """ Prettier (non-repr-like) and more informative printer for SList """
243 # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
243 # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
244 # if hasattr(arg, 'hideonce') and arg.hideonce:
244 # if hasattr(arg, 'hideonce') and arg.hideonce:
245 # arg.hideonce = False
245 # arg.hideonce = False
246 # return
246 # return
247 #
247 #
248 # nlprint(arg) # This was a nested list printer, now removed.
248 # nlprint(arg) # This was a nested list printer, now removed.
249 #
249 #
250 # print_slist = result_display.when_type(SList)(print_slist)
250 # print_slist = result_display.when_type(SList)(print_slist)
251
251
252
252
253 def indent(instr,nspaces=4, ntabs=0, flatten=False):
253 def indent(instr,nspaces=4, ntabs=0, flatten=False):
254 """Indent a string a given number of spaces or tabstops.
254 """Indent a string a given number of spaces or tabstops.
255
255
256 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
256 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
257
257
258 Parameters
258 Parameters
259 ----------
259 ----------
260
260
261 instr : basestring
261 instr : basestring
262 The string to be indented.
262 The string to be indented.
263 nspaces : int (default: 4)
263 nspaces : int (default: 4)
264 The number of spaces to be indented.
264 The number of spaces to be indented.
265 ntabs : int (default: 0)
265 ntabs : int (default: 0)
266 The number of tabs to be indented.
266 The number of tabs to be indented.
267 flatten : bool (default: False)
267 flatten : bool (default: False)
268 Whether to scrub existing indentation. If True, all lines will be
268 Whether to scrub existing indentation. If True, all lines will be
269 aligned to the same indentation. If False, existing indentation will
269 aligned to the same indentation. If False, existing indentation will
270 be strictly increased.
270 be strictly increased.
271
271
272 Returns
272 Returns
273 -------
273 -------
274
274
275 str|unicode : string indented by ntabs and nspaces.
275 str|unicode : string indented by ntabs and nspaces.
276
276
277 """
277 """
278 if instr is None:
278 if instr is None:
279 return
279 return
280 ind = '\t'*ntabs+' '*nspaces
280 ind = '\t'*ntabs+' '*nspaces
281 if flatten:
281 if flatten:
282 pat = re.compile(r'^\s*', re.MULTILINE)
282 pat = re.compile(r'^\s*', re.MULTILINE)
283 else:
283 else:
284 pat = re.compile(r'^', re.MULTILINE)
284 pat = re.compile(r'^', re.MULTILINE)
285 outstr = re.sub(pat, ind, instr)
285 outstr = re.sub(pat, ind, instr)
286 if outstr.endswith(os.linesep+ind):
286 if outstr.endswith(os.linesep+ind):
287 return outstr[:-len(ind)]
287 return outstr[:-len(ind)]
288 else:
288 else:
289 return outstr
289 return outstr
290
290
291
291
292 def list_strings(arg):
292 def list_strings(arg):
293 """Always return a list of strings, given a string or list of strings
293 """Always return a list of strings, given a string or list of strings
294 as input.
294 as input.
295
295
296 Examples
296 Examples
297 --------
297 --------
298 ::
298 ::
299
299
300 In [7]: list_strings('A single string')
300 In [7]: list_strings('A single string')
301 Out[7]: ['A single string']
301 Out[7]: ['A single string']
302
302
303 In [8]: list_strings(['A single string in a list'])
303 In [8]: list_strings(['A single string in a list'])
304 Out[8]: ['A single string in a list']
304 Out[8]: ['A single string in a list']
305
305
306 In [9]: list_strings(['A','list','of','strings'])
306 In [9]: list_strings(['A','list','of','strings'])
307 Out[9]: ['A', 'list', 'of', 'strings']
307 Out[9]: ['A', 'list', 'of', 'strings']
308 """
308 """
309
309
310 if isinstance(arg, py3compat.string_types): return [arg]
310 if isinstance(arg, py3compat.string_types): return [arg]
311 else: return arg
311 else: return arg
312
312
313
313
314 def marquee(txt='',width=78,mark='*'):
314 def marquee(txt='',width=78,mark='*'):
315 """Return the input string centered in a 'marquee'.
315 """Return the input string centered in a 'marquee'.
316
316
317 Examples
317 Examples
318 --------
318 --------
319 ::
319 ::
320
320
321 In [16]: marquee('A test',40)
321 In [16]: marquee('A test',40)
322 Out[16]: '**************** A test ****************'
322 Out[16]: '**************** A test ****************'
323
323
324 In [17]: marquee('A test',40,'-')
324 In [17]: marquee('A test',40,'-')
325 Out[17]: '---------------- A test ----------------'
325 Out[17]: '---------------- A test ----------------'
326
326
327 In [18]: marquee('A test',40,' ')
327 In [18]: marquee('A test',40,' ')
328 Out[18]: ' A test '
328 Out[18]: ' A test '
329
329
330 """
330 """
331 if not txt:
331 if not txt:
332 return (mark*width)[:width]
332 return (mark*width)[:width]
333 nmark = (width-len(txt)-2)//len(mark)//2
333 nmark = (width-len(txt)-2)//len(mark)//2
334 if nmark < 0: nmark =0
334 if nmark < 0: nmark =0
335 marks = mark*nmark
335 marks = mark*nmark
336 return '%s %s %s' % (marks,txt,marks)
336 return '%s %s %s' % (marks,txt,marks)
337
337
338
338
339 ini_spaces_re = re.compile(r'^(\s+)')
339 ini_spaces_re = re.compile(r'^(\s+)')
340
340
341 def num_ini_spaces(strng):
341 def num_ini_spaces(strng):
342 """Return the number of initial spaces in a string"""
342 """Return the number of initial spaces in a string"""
343
343
344 ini_spaces = ini_spaces_re.match(strng)
344 ini_spaces = ini_spaces_re.match(strng)
345 if ini_spaces:
345 if ini_spaces:
346 return ini_spaces.end()
346 return ini_spaces.end()
347 else:
347 else:
348 return 0
348 return 0
349
349
350
350
351 def format_screen(strng):
351 def format_screen(strng):
352 """Format a string for screen printing.
352 """Format a string for screen printing.
353
353
354 This removes some latex-type format codes."""
354 This removes some latex-type format codes."""
355 # Paragraph continue
355 # Paragraph continue
356 par_re = re.compile(r'\\$',re.MULTILINE)
356 par_re = re.compile(r'\\$',re.MULTILINE)
357 strng = par_re.sub('',strng)
357 strng = par_re.sub('',strng)
358 return strng
358 return strng
359
359
360
360
361 def dedent(text):
361 def dedent(text):
362 """Equivalent of textwrap.dedent that ignores unindented first line.
362 """Equivalent of textwrap.dedent that ignores unindented first line.
363
363
364 This means it will still dedent strings like:
364 This means it will still dedent strings like:
365 '''foo
365 '''foo
366 is a bar
366 is a bar
367 '''
367 '''
368
368
369 For use in wrap_paragraphs.
369 For use in wrap_paragraphs.
370 """
370 """
371
371
372 if text.startswith('\n'):
372 if text.startswith('\n'):
373 # text starts with blank line, don't ignore the first line
373 # text starts with blank line, don't ignore the first line
374 return textwrap.dedent(text)
374 return textwrap.dedent(text)
375
375
376 # split first line
376 # split first line
377 splits = text.split('\n',1)
377 splits = text.split('\n',1)
378 if len(splits) == 1:
378 if len(splits) == 1:
379 # only one line
379 # only one line
380 return textwrap.dedent(text)
380 return textwrap.dedent(text)
381
381
382 first, rest = splits
382 first, rest = splits
383 # dedent everything but the first line
383 # dedent everything but the first line
384 rest = textwrap.dedent(rest)
384 rest = textwrap.dedent(rest)
385 return '\n'.join([first, rest])
385 return '\n'.join([first, rest])
386
386
387
387
388 def wrap_paragraphs(text, ncols=80):
388 def wrap_paragraphs(text, ncols=80):
389 """Wrap multiple paragraphs to fit a specified width.
389 """Wrap multiple paragraphs to fit a specified width.
390
390
391 This is equivalent to textwrap.wrap, but with support for multiple
391 This is equivalent to textwrap.wrap, but with support for multiple
392 paragraphs, as separated by empty lines.
392 paragraphs, as separated by empty lines.
393
393
394 Returns
394 Returns
395 -------
395 -------
396
396
397 list of complete paragraphs, wrapped to fill `ncols` columns.
397 list of complete paragraphs, wrapped to fill `ncols` columns.
398 """
398 """
399 paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
399 paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
400 text = dedent(text).strip()
400 text = dedent(text).strip()
401 paragraphs = paragraph_re.split(text)[::2] # every other entry is space
401 paragraphs = paragraph_re.split(text)[::2] # every other entry is space
402 out_ps = []
402 out_ps = []
403 indent_re = re.compile(r'\n\s+', re.MULTILINE)
403 indent_re = re.compile(r'\n\s+', re.MULTILINE)
404 for p in paragraphs:
404 for p in paragraphs:
405 # presume indentation that survives dedent is meaningful formatting,
405 # presume indentation that survives dedent is meaningful formatting,
406 # so don't fill unless text is flush.
406 # so don't fill unless text is flush.
407 if indent_re.search(p) is None:
407 if indent_re.search(p) is None:
408 # wrap paragraph
408 # wrap paragraph
409 p = textwrap.fill(p, ncols)
409 p = textwrap.fill(p, ncols)
410 out_ps.append(p)
410 out_ps.append(p)
411 return out_ps
411 return out_ps
412
412
413
413
414 def long_substr(data):
414 def long_substr(data):
415 """Return the longest common substring in a list of strings.
415 """Return the longest common substring in a list of strings.
416
416
417 Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
417 Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
418 """
418 """
419 substr = ''
419 substr = ''
420 if len(data) > 1 and len(data[0]) > 0:
420 if len(data) > 1 and len(data[0]) > 0:
421 for i in range(len(data[0])):
421 for i in range(len(data[0])):
422 for j in range(len(data[0])-i+1):
422 for j in range(len(data[0])-i+1):
423 if j > len(substr) and all(data[0][i:i+j] in x for x in data):
423 if j > len(substr) and all(data[0][i:i+j] in x for x in data):
424 substr = data[0][i:i+j]
424 substr = data[0][i:i+j]
425 elif len(data) == 1:
425 elif len(data) == 1:
426 substr = data[0]
426 substr = data[0]
427 return substr
427 return substr
428
428
429
429
430 def strip_email_quotes(text):
430 def strip_email_quotes(text):
431 """Strip leading email quotation characters ('>').
431 """Strip leading email quotation characters ('>').
432
432
433 Removes any combination of leading '>' interspersed with whitespace that
433 Removes any combination of leading '>' interspersed with whitespace that
434 appears *identically* in all lines of the input text.
434 appears *identically* in all lines of the input text.
435
435
436 Parameters
436 Parameters
437 ----------
437 ----------
438 text : str
438 text : str
439
439
440 Examples
440 Examples
441 --------
441 --------
442
442
443 Simple uses::
443 Simple uses::
444
444
445 In [2]: strip_email_quotes('> > text')
445 In [2]: strip_email_quotes('> > text')
446 Out[2]: 'text'
446 Out[2]: 'text'
447
447
448 In [3]: strip_email_quotes('> > text\\n> > more')
448 In [3]: strip_email_quotes('> > text\\n> > more')
449 Out[3]: 'text\\nmore'
449 Out[3]: 'text\\nmore'
450
450
451 Note how only the common prefix that appears in all lines is stripped::
451 Note how only the common prefix that appears in all lines is stripped::
452
452
453 In [4]: strip_email_quotes('> > text\\n> > more\\n> more...')
453 In [4]: strip_email_quotes('> > text\\n> > more\\n> more...')
454 Out[4]: '> text\\n> more\\nmore...'
454 Out[4]: '> text\\n> more\\nmore...'
455
455
456 So if any line has no quote marks ('>') , then none are stripped from any
456 So if any line has no quote marks ('>') , then none are stripped from any
457 of them ::
457 of them ::
458
458
459 In [5]: strip_email_quotes('> > text\\n> > more\\nlast different')
459 In [5]: strip_email_quotes('> > text\\n> > more\\nlast different')
460 Out[5]: '> > text\\n> > more\\nlast different'
460 Out[5]: '> > text\\n> > more\\nlast different'
461 """
461 """
462 lines = text.splitlines()
462 lines = text.splitlines()
463 matches = set()
463 matches = set()
464 for line in lines:
464 for line in lines:
465 prefix = re.match(r'^(\s*>[ >]*)', line)
465 prefix = re.match(r'^(\s*>[ >]*)', line)
466 if prefix:
466 if prefix:
467 matches.add(prefix.group(1))
467 matches.add(prefix.group(1))
468 else:
468 else:
469 break
469 break
470 else:
470 else:
471 prefix = long_substr(list(matches))
471 prefix = long_substr(list(matches))
472 if prefix:
472 if prefix:
473 strip = len(prefix)
473 strip = len(prefix)
474 text = '\n'.join([ ln[strip:] for ln in lines])
474 text = '\n'.join([ ln[strip:] for ln in lines])
475 return text
475 return text
476
476
477 def strip_ansi(source):
477 def strip_ansi(source):
478 """
478 """
479 Remove ansi escape codes from text.
479 Remove ansi escape codes from text.
480
480
481 Parameters
481 Parameters
482 ----------
482 ----------
483 source : str
483 source : str
484 Source to remove the ansi from
484 Source to remove the ansi from
485 """
485 """
486 return re.sub(r'\033\[(\d|;)+?m', '', source)
486 return re.sub(r'\033\[(\d|;)+?m', '', source)
487
487
488
488
489 class EvalFormatter(Formatter):
489 class EvalFormatter(Formatter):
490 """A String Formatter that allows evaluation of simple expressions.
490 """A String Formatter that allows evaluation of simple expressions.
491
491
492 Note that this version interprets a : as specifying a format string (as per
492 Note that this version interprets a : as specifying a format string (as per
493 standard string formatting), so if slicing is required, you must explicitly
493 standard string formatting), so if slicing is required, you must explicitly
494 create a slice.
494 create a slice.
495
495
496 This is to be used in templating cases, such as the parallel batch
496 This is to be used in templating cases, such as the parallel batch
497 script templates, where simple arithmetic on arguments is useful.
497 script templates, where simple arithmetic on arguments is useful.
498
498
499 Examples
499 Examples
500 --------
500 --------
501 ::
501 ::
502
502
503 In [1]: f = EvalFormatter()
503 In [1]: f = EvalFormatter()
504 In [2]: f.format('{n//4}', n=8)
504 In [2]: f.format('{n//4}', n=8)
505 Out[2]: '2'
505 Out[2]: '2'
506
506
507 In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
507 In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello")
508 Out[3]: 'll'
508 Out[3]: 'll'
509 """
509 """
510 def get_field(self, name, args, kwargs):
510 def get_field(self, name, args, kwargs):
511 v = eval(name, kwargs)
511 v = eval(name, kwargs)
512 return v, name
512 return v, name
513
513
514 #XXX: As of Python 3.4, the format string parsing no longer splits on a colon
514 #XXX: As of Python 3.4, the format string parsing no longer splits on a colon
515 # inside [], so EvalFormatter can handle slicing. Once we only support 3.4 and
515 # inside [], so EvalFormatter can handle slicing. Once we only support 3.4 and
516 # above, it should be possible to remove FullEvalFormatter.
516 # above, it should be possible to remove FullEvalFormatter.
517
517
518 class FullEvalFormatter(Formatter):
518 class FullEvalFormatter(Formatter):
519 """A String Formatter that allows evaluation of simple expressions.
519 """A String Formatter that allows evaluation of simple expressions.
520
520
521 Any time a format key is not found in the kwargs,
521 Any time a format key is not found in the kwargs,
522 it will be tried as an expression in the kwargs namespace.
522 it will be tried as an expression in the kwargs namespace.
523
523
524 Note that this version allows slicing using [1:2], so you cannot specify
524 Note that this version allows slicing using [1:2], so you cannot specify
525 a format string. Use :class:`EvalFormatter` to permit format strings.
525 a format string. Use :class:`EvalFormatter` to permit format strings.
526
526
527 Examples
527 Examples
528 --------
528 --------
529 ::
529 ::
530
530
531 In [1]: f = FullEvalFormatter()
531 In [1]: f = FullEvalFormatter()
532 In [2]: f.format('{n//4}', n=8)
532 In [2]: f.format('{n//4}', n=8)
533 Out[2]: '2'
533 Out[2]: '2'
534
534
535 In [3]: f.format('{list(range(5))[2:4]}')
535 In [3]: f.format('{list(range(5))[2:4]}')
536 Out[3]: '[2, 3]'
536 Out[3]: '[2, 3]'
537
537
538 In [4]: f.format('{3*2}')
538 In [4]: f.format('{3*2}')
539 Out[4]: '6'
539 Out[4]: '6'
540 """
540 """
541 # copied from Formatter._vformat with minor changes to allow eval
541 # copied from Formatter._vformat with minor changes to allow eval
542 # and replace the format_spec code with slicing
542 # and replace the format_spec code with slicing
543 def vformat(self, format_string, args, kwargs):
543 def vformat(self, format_string, args, kwargs):
544 result = []
544 result = []
545 for literal_text, field_name, format_spec, conversion in \
545 for literal_text, field_name, format_spec, conversion in \
546 self.parse(format_string):
546 self.parse(format_string):
547
547
548 # output the literal text
548 # output the literal text
549 if literal_text:
549 if literal_text:
550 result.append(literal_text)
550 result.append(literal_text)
551
551
552 # if there's a field, output it
552 # if there's a field, output it
553 if field_name is not None:
553 if field_name is not None:
554 # this is some markup, find the object and do
554 # this is some markup, find the object and do
555 # the formatting
555 # the formatting
556
556
557 if format_spec:
557 if format_spec:
558 # override format spec, to allow slicing:
558 # override format spec, to allow slicing:
559 field_name = ':'.join([field_name, format_spec])
559 field_name = ':'.join([field_name, format_spec])
560
560
561 # eval the contents of the field for the object
561 # eval the contents of the field for the object
562 # to be formatted
562 # to be formatted
563 obj = eval(field_name, kwargs)
563 obj = eval(field_name, kwargs)
564
564
565 # do any conversion on the resulting object
565 # do any conversion on the resulting object
566 obj = self.convert_field(obj, conversion)
566 obj = self.convert_field(obj, conversion)
567
567
568 # format the object and append to the result
568 # format the object and append to the result
569 result.append(self.format_field(obj, ''))
569 result.append(self.format_field(obj, ''))
570
570
571 return u''.join(py3compat.cast_unicode(s) for s in result)
571 return u''.join(py3compat.cast_unicode(s) for s in result)
572
572
573
573
574 class DollarFormatter(FullEvalFormatter):
574 class DollarFormatter(FullEvalFormatter):
575 """Formatter allowing Itpl style $foo replacement, for names and attribute
575 """Formatter allowing Itpl style $foo replacement, for names and attribute
576 access only. Standard {foo} replacement also works, and allows full
576 access only. Standard {foo} replacement also works, and allows full
577 evaluation of its arguments.
577 evaluation of its arguments.
578
578
579 Examples
579 Examples
580 --------
580 --------
581 ::
581 ::
582
582
583 In [1]: f = DollarFormatter()
583 In [1]: f = DollarFormatter()
584 In [2]: f.format('{n//4}', n=8)
584 In [2]: f.format('{n//4}', n=8)
585 Out[2]: '2'
585 Out[2]: '2'
586
586
587 In [3]: f.format('23 * 76 is $result', result=23*76)
587 In [3]: f.format('23 * 76 is $result', result=23*76)
588 Out[3]: '23 * 76 is 1748'
588 Out[3]: '23 * 76 is 1748'
589
589
590 In [4]: f.format('$a or {b}', a=1, b=2)
590 In [4]: f.format('$a or {b}', a=1, b=2)
591 Out[4]: '1 or 2'
591 Out[4]: '1 or 2'
592 """
592 """
593 _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)")
593 _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)")
594 def parse(self, fmt_string):
594 def parse(self, fmt_string):
595 for literal_txt, field_name, format_spec, conversion \
595 for literal_txt, field_name, format_spec, conversion \
596 in Formatter.parse(self, fmt_string):
596 in Formatter.parse(self, fmt_string):
597
597
598 # Find $foo patterns in the literal text.
598 # Find $foo patterns in the literal text.
599 continue_from = 0
599 continue_from = 0
600 txt = ""
600 txt = ""
601 for m in self._dollar_pattern.finditer(literal_txt):
601 for m in self._dollar_pattern.finditer(literal_txt):
602 new_txt, new_field = m.group(1,2)
602 new_txt, new_field = m.group(1,2)
603 # $$foo --> $foo
603 # $$foo --> $foo
604 if new_field.startswith("$"):
604 if new_field.startswith("$"):
605 txt += new_txt + new_field
605 txt += new_txt + new_field
606 else:
606 else:
607 yield (txt + new_txt, new_field, "", None)
607 yield (txt + new_txt, new_field, "", None)
608 txt = ""
608 txt = ""
609 continue_from = m.end()
609 continue_from = m.end()
610
610
611 # Re-yield the {foo} style pattern
611 # Re-yield the {foo} style pattern
612 yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion)
612 yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion)
613
613
614 #-----------------------------------------------------------------------------
614 #-----------------------------------------------------------------------------
615 # Utils to columnize a list of string
615 # Utils to columnize a list of string
616 #-----------------------------------------------------------------------------
616 #-----------------------------------------------------------------------------
617
617
618 def _col_chunks(l, max_rows, row_first=False):
618 def _col_chunks(l, max_rows, row_first=False):
619 """Yield successive max_rows-sized column chunks from l."""
619 """Yield successive max_rows-sized column chunks from l."""
620 if row_first:
620 if row_first:
621 ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
621 ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
622 for i in py3compat.xrange(ncols):
622 for i in range(ncols):
623 yield [l[j] for j in py3compat.xrange(i, len(l), ncols)]
623 yield [l[j] for j in range(i, len(l), ncols)]
624 else:
624 else:
625 for i in py3compat.xrange(0, len(l), max_rows):
625 for i in range(0, len(l), max_rows):
626 yield l[i:(i + max_rows)]
626 yield l[i:(i + max_rows)]
627
627
628
628
629 def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
629 def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80):
630 """Calculate optimal info to columnize a list of string"""
630 """Calculate optimal info to columnize a list of string"""
631 for max_rows in range(1, len(rlist) + 1):
631 for max_rows in range(1, len(rlist) + 1):
632 col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
632 col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first)))
633 sumlength = sum(col_widths)
633 sumlength = sum(col_widths)
634 ncols = len(col_widths)
634 ncols = len(col_widths)
635 if sumlength + separator_size * (ncols - 1) <= displaywidth:
635 if sumlength + separator_size * (ncols - 1) <= displaywidth:
636 break
636 break
637 return {'num_columns': ncols,
637 return {'num_columns': ncols,
638 'optimal_separator_width': (displaywidth - sumlength) // (ncols - 1) if (ncols - 1) else 0,
638 'optimal_separator_width': (displaywidth - sumlength) // (ncols - 1) if (ncols - 1) else 0,
639 'max_rows': max_rows,
639 'max_rows': max_rows,
640 'column_widths': col_widths
640 'column_widths': col_widths
641 }
641 }
642
642
643
643
644 def _get_or_default(mylist, i, default=None):
644 def _get_or_default(mylist, i, default=None):
645 """return list item number, or default if don't exist"""
645 """return list item number, or default if don't exist"""
646 if i >= len(mylist):
646 if i >= len(mylist):
647 return default
647 return default
648 else :
648 else :
649 return mylist[i]
649 return mylist[i]
650
650
651
651
652 def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
652 def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) :
653 """Returns a nested list, and info to columnize items
653 """Returns a nested list, and info to columnize items
654
654
655 Parameters
655 Parameters
656 ----------
656 ----------
657
657
658 items
658 items
659 list of strings to columize
659 list of strings to columize
660 row_first : (default False)
660 row_first : (default False)
661 Whether to compute columns for a row-first matrix instead of
661 Whether to compute columns for a row-first matrix instead of
662 column-first (default).
662 column-first (default).
663 empty : (default None)
663 empty : (default None)
664 default value to fill list if needed
664 default value to fill list if needed
665 separator_size : int (default=2)
665 separator_size : int (default=2)
666 How much caracters will be used as a separation between each columns.
666 How much caracters will be used as a separation between each columns.
667 displaywidth : int (default=80)
667 displaywidth : int (default=80)
668 The width of the area onto wich the columns should enter
668 The width of the area onto wich the columns should enter
669
669
670 Returns
670 Returns
671 -------
671 -------
672
672
673 strings_matrix
673 strings_matrix
674
674
675 nested list of string, the outer most list contains as many list as
675 nested list of string, the outer most list contains as many list as
676 rows, the innermost lists have each as many element as colums. If the
676 rows, the innermost lists have each as many element as colums. If the
677 total number of elements in `items` does not equal the product of
677 total number of elements in `items` does not equal the product of
678 rows*columns, the last element of some lists are filled with `None`.
678 rows*columns, the last element of some lists are filled with `None`.
679
679
680 dict_info
680 dict_info
681 some info to make columnize easier:
681 some info to make columnize easier:
682
682
683 num_columns
683 num_columns
684 number of columns
684 number of columns
685 max_rows
685 max_rows
686 maximum number of rows (final number may be less)
686 maximum number of rows (final number may be less)
687 column_widths
687 column_widths
688 list of with of each columns
688 list of with of each columns
689 optimal_separator_width
689 optimal_separator_width
690 best separator width between columns
690 best separator width between columns
691
691
692 Examples
692 Examples
693 --------
693 --------
694 ::
694 ::
695
695
696 In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
696 In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l']
697 In [2]: list, info = compute_item_matrix(l, displaywidth=12)
697 In [2]: list, info = compute_item_matrix(l, displaywidth=12)
698 In [3]: list
698 In [3]: list
699 Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]]
699 Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]]
700 In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5}
700 In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5}
701 In [5]: all((info[k] == ideal[k] for k in ideal.keys()))
701 In [5]: all((info[k] == ideal[k] for k in ideal.keys()))
702 Out[5]: True
702 Out[5]: True
703 """
703 """
704 info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
704 info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs)
705 nrow, ncol = info['max_rows'], info['num_columns']
705 nrow, ncol = info['max_rows'], info['num_columns']
706 if row_first:
706 if row_first:
707 return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
707 return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info)
708 else:
708 else:
709 return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
709 return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info)
710
710
711
711
712 def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False):
712 def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False):
713 """ Transform a list of strings into a single string with columns.
713 """ Transform a list of strings into a single string with columns.
714
714
715 Parameters
715 Parameters
716 ----------
716 ----------
717 items : sequence of strings
717 items : sequence of strings
718 The strings to process.
718 The strings to process.
719
719
720 row_first : (default False)
720 row_first : (default False)
721 Whether to compute columns for a row-first matrix instead of
721 Whether to compute columns for a row-first matrix instead of
722 column-first (default).
722 column-first (default).
723
723
724 separator : str, optional [default is two spaces]
724 separator : str, optional [default is two spaces]
725 The string that separates columns.
725 The string that separates columns.
726
726
727 displaywidth : int, optional [default is 80]
727 displaywidth : int, optional [default is 80]
728 Width of the display in number of characters.
728 Width of the display in number of characters.
729
729
730 Returns
730 Returns
731 -------
731 -------
732 The formatted string.
732 The formatted string.
733 """
733 """
734 if not items:
734 if not items:
735 return '\n'
735 return '\n'
736 matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
736 matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth)
737 if spread:
737 if spread:
738 separator = separator.ljust(int(info['optimal_separator_width']))
738 separator = separator.ljust(int(info['optimal_separator_width']))
739 fmatrix = [filter(None, x) for x in matrix]
739 fmatrix = [filter(None, x) for x in matrix]
740 sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
740 sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])])
741 return '\n'.join(map(sjoin, fmatrix))+'\n'
741 return '\n'.join(map(sjoin, fmatrix))+'\n'
742
742
743
743
744 def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
744 def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""):
745 """
745 """
746 Return a string with a natural enumeration of items
746 Return a string with a natural enumeration of items
747
747
748 >>> get_text_list(['a', 'b', 'c', 'd'])
748 >>> get_text_list(['a', 'b', 'c', 'd'])
749 'a, b, c and d'
749 'a, b, c and d'
750 >>> get_text_list(['a', 'b', 'c'], ' or ')
750 >>> get_text_list(['a', 'b', 'c'], ' or ')
751 'a, b or c'
751 'a, b or c'
752 >>> get_text_list(['a', 'b', 'c'], ', ')
752 >>> get_text_list(['a', 'b', 'c'], ', ')
753 'a, b, c'
753 'a, b, c'
754 >>> get_text_list(['a', 'b'], ' or ')
754 >>> get_text_list(['a', 'b'], ' or ')
755 'a or b'
755 'a or b'
756 >>> get_text_list(['a'])
756 >>> get_text_list(['a'])
757 'a'
757 'a'
758 >>> get_text_list([])
758 >>> get_text_list([])
759 ''
759 ''
760 >>> get_text_list(['a', 'b'], wrap_item_with="`")
760 >>> get_text_list(['a', 'b'], wrap_item_with="`")
761 '`a` and `b`'
761 '`a` and `b`'
762 >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
762 >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ")
763 'a + b + c = d'
763 'a + b + c = d'
764 """
764 """
765 if len(list_) == 0:
765 if len(list_) == 0:
766 return ''
766 return ''
767 if wrap_item_with:
767 if wrap_item_with:
768 list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for
768 list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for
769 item in list_]
769 item in list_]
770 if len(list_) == 1:
770 if len(list_) == 1:
771 return list_[0]
771 return list_[0]
772 return '%s%s%s' % (
772 return '%s%s%s' % (
773 sep.join(i for i in list_[:-1]),
773 sep.join(i for i in list_[:-1]),
774 last_sep, list_[-1])
774 last_sep, list_[-1])
@@ -1,118 +1,116 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for timing code execution.
3 Utilities for timing code execution.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import time
17 import time
18
18
19 from .py3compat import xrange
20
21 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
22 # Code
20 # Code
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
24
22
25 # If possible (Unix), use the resource module instead of time.clock()
23 # If possible (Unix), use the resource module instead of time.clock()
26 try:
24 try:
27 import resource
25 import resource
28 def clocku():
26 def clocku():
29 """clocku() -> floating point number
27 """clocku() -> floating point number
30
28
31 Return the *USER* CPU time in seconds since the start of the process.
29 Return the *USER* CPU time in seconds since the start of the process.
32 This is done via a call to resource.getrusage, so it avoids the
30 This is done via a call to resource.getrusage, so it avoids the
33 wraparound problems in time.clock()."""
31 wraparound problems in time.clock()."""
34
32
35 return resource.getrusage(resource.RUSAGE_SELF)[0]
33 return resource.getrusage(resource.RUSAGE_SELF)[0]
36
34
37 def clocks():
35 def clocks():
38 """clocks() -> floating point number
36 """clocks() -> floating point number
39
37
40 Return the *SYSTEM* CPU time in seconds since the start of the process.
38 Return the *SYSTEM* CPU time in seconds since the start of the process.
41 This is done via a call to resource.getrusage, so it avoids the
39 This is done via a call to resource.getrusage, so it avoids the
42 wraparound problems in time.clock()."""
40 wraparound problems in time.clock()."""
43
41
44 return resource.getrusage(resource.RUSAGE_SELF)[1]
42 return resource.getrusage(resource.RUSAGE_SELF)[1]
45
43
46 def clock():
44 def clock():
47 """clock() -> floating point number
45 """clock() -> floating point number
48
46
49 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
47 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
50 the process. This is done via a call to resource.getrusage, so it
48 the process. This is done via a call to resource.getrusage, so it
51 avoids the wraparound problems in time.clock()."""
49 avoids the wraparound problems in time.clock()."""
52
50
53 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
51 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
54 return u+s
52 return u+s
55
53
56 def clock2():
54 def clock2():
57 """clock2() -> (t_user,t_system)
55 """clock2() -> (t_user,t_system)
58
56
59 Similar to clock(), but return a tuple of user/system times."""
57 Similar to clock(), but return a tuple of user/system times."""
60 return resource.getrusage(resource.RUSAGE_SELF)[:2]
58 return resource.getrusage(resource.RUSAGE_SELF)[:2]
61 except ImportError:
59 except ImportError:
62 # There is no distinction of user/system time under windows, so we just use
60 # There is no distinction of user/system time under windows, so we just use
63 # time.clock() for everything...
61 # time.clock() for everything...
64 clocku = clocks = clock = time.clock
62 clocku = clocks = clock = time.clock
65 def clock2():
63 def clock2():
66 """Under windows, system CPU time can't be measured.
64 """Under windows, system CPU time can't be measured.
67
65
68 This just returns clock() and zero."""
66 This just returns clock() and zero."""
69 return time.clock(),0.0
67 return time.clock(),0.0
70
68
71
69
72 def timings_out(reps,func,*args,**kw):
70 def timings_out(reps,func,*args,**kw):
73 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
71 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
74
72
75 Execute a function reps times, return a tuple with the elapsed total
73 Execute a function reps times, return a tuple with the elapsed total
76 CPU time in seconds, the time per call and the function's output.
74 CPU time in seconds, the time per call and the function's output.
77
75
78 Under Unix, the return value is the sum of user+system time consumed by
76 Under Unix, the return value is the sum of user+system time consumed by
79 the process, computed via the resource module. This prevents problems
77 the process, computed via the resource module. This prevents problems
80 related to the wraparound effect which the time.clock() function has.
78 related to the wraparound effect which the time.clock() function has.
81
79
82 Under Windows the return value is in wall clock seconds. See the
80 Under Windows the return value is in wall clock seconds. See the
83 documentation for the time module for more details."""
81 documentation for the time module for more details."""
84
82
85 reps = int(reps)
83 reps = int(reps)
86 assert reps >=1, 'reps must be >= 1'
84 assert reps >=1, 'reps must be >= 1'
87 if reps==1:
85 if reps==1:
88 start = clock()
86 start = clock()
89 out = func(*args,**kw)
87 out = func(*args,**kw)
90 tot_time = clock()-start
88 tot_time = clock()-start
91 else:
89 else:
92 rng = xrange(reps-1) # the last time is executed separately to store output
90 rng = range(reps-1) # the last time is executed separately to store output
93 start = clock()
91 start = clock()
94 for dummy in rng: func(*args,**kw)
92 for dummy in rng: func(*args,**kw)
95 out = func(*args,**kw) # one last time
93 out = func(*args,**kw) # one last time
96 tot_time = clock()-start
94 tot_time = clock()-start
97 av_time = tot_time / reps
95 av_time = tot_time / reps
98 return tot_time,av_time,out
96 return tot_time,av_time,out
99
97
100
98
101 def timings(reps,func,*args,**kw):
99 def timings(reps,func,*args,**kw):
102 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
100 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
103
101
104 Execute a function reps times, return a tuple with the elapsed total CPU
102 Execute a function reps times, return a tuple with the elapsed total CPU
105 time in seconds and the time per call. These are just the first two values
103 time in seconds and the time per call. These are just the first two values
106 in timings_out()."""
104 in timings_out()."""
107
105
108 return timings_out(reps,func,*args,**kw)[0:2]
106 return timings_out(reps,func,*args,**kw)[0:2]
109
107
110
108
111 def timing(func,*args,**kw):
109 def timing(func,*args,**kw):
112 """timing(func,*args,**kw) -> t_total
110 """timing(func,*args,**kw) -> t_total
113
111
114 Execute a function once, return the elapsed total CPU time in
112 Execute a function once, return the elapsed total CPU time in
115 seconds. This is just the first value in timings_out()."""
113 seconds. This is just the first value in timings_out()."""
116
114
117 return timings_out(1,func,*args,**kw)[0]
115 return timings_out(1,func,*args,**kw)[0]
118
116
@@ -1,112 +1,111 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Support for wildcard pattern matching in object inspection.
2 """Support for wildcard pattern matching in object inspection.
3
3
4 Authors
4 Authors
5 -------
5 -------
6 - JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
6 - JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
7 - Thomas Kluyver
7 - Thomas Kluyver
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2005 JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
11 # Copyright (C) 2005 JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 import re
17 import re
18 import types
18 import types
19
19
20 from IPython.utils.dir2 import dir2
20 from IPython.utils.dir2 import dir2
21 from .py3compat import iteritems
22
21
23 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
22 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
24 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
23 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
25 objects from the types package, and vice versa."""
24 objects from the types package, and vice versa."""
26 typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
25 typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
27 typestr2type, type2typestr = {}, {}
26 typestr2type, type2typestr = {}, {}
28
27
29 for tname in typenamelist:
28 for tname in typenamelist:
30 name = tname[:-4].lower() # Cut 'Type' off the end of the name
29 name = tname[:-4].lower() # Cut 'Type' off the end of the name
31 obj = getattr(types, tname)
30 obj = getattr(types, tname)
32 typestr2type[name] = obj
31 typestr2type[name] = obj
33 if name not in dont_include_in_type2typestr:
32 if name not in dont_include_in_type2typestr:
34 type2typestr[obj] = name
33 type2typestr[obj] = name
35 return typestr2type, type2typestr
34 return typestr2type, type2typestr
36
35
37 typestr2type, type2typestr = create_typestr2type_dicts()
36 typestr2type, type2typestr = create_typestr2type_dicts()
38
37
39 def is_type(obj, typestr_or_type):
38 def is_type(obj, typestr_or_type):
40 """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
39 """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
41 can take strings or actual python types for the second argument, i.e.
40 can take strings or actual python types for the second argument, i.e.
42 'tuple'<->TupleType. 'all' matches all types.
41 'tuple'<->TupleType. 'all' matches all types.
43
42
44 TODO: Should be extended for choosing more than one type."""
43 TODO: Should be extended for choosing more than one type."""
45 if typestr_or_type == "all":
44 if typestr_or_type == "all":
46 return True
45 return True
47 if type(typestr_or_type) == type:
46 if type(typestr_or_type) == type:
48 test_type = typestr_or_type
47 test_type = typestr_or_type
49 else:
48 else:
50 test_type = typestr2type.get(typestr_or_type, False)
49 test_type = typestr2type.get(typestr_or_type, False)
51 if test_type:
50 if test_type:
52 return isinstance(obj, test_type)
51 return isinstance(obj, test_type)
53 return False
52 return False
54
53
55 def show_hidden(str, show_all=False):
54 def show_hidden(str, show_all=False):
56 """Return true for strings starting with single _ if show_all is true."""
55 """Return true for strings starting with single _ if show_all is true."""
57 return show_all or str.startswith("__") or not str.startswith("_")
56 return show_all or str.startswith("__") or not str.startswith("_")
58
57
59 def dict_dir(obj):
58 def dict_dir(obj):
60 """Produce a dictionary of an object's attributes. Builds on dir2 by
59 """Produce a dictionary of an object's attributes. Builds on dir2 by
61 checking that a getattr() call actually succeeds."""
60 checking that a getattr() call actually succeeds."""
62 ns = {}
61 ns = {}
63 for key in dir2(obj):
62 for key in dir2(obj):
64 # This seemingly unnecessary try/except is actually needed
63 # This seemingly unnecessary try/except is actually needed
65 # because there is code out there with metaclasses that
64 # because there is code out there with metaclasses that
66 # create 'write only' attributes, where a getattr() call
65 # create 'write only' attributes, where a getattr() call
67 # will fail even if the attribute appears listed in the
66 # will fail even if the attribute appears listed in the
68 # object's dictionary. Properties can actually do the same
67 # object's dictionary. Properties can actually do the same
69 # thing. In particular, Traits use this pattern
68 # thing. In particular, Traits use this pattern
70 try:
69 try:
71 ns[key] = getattr(obj, key)
70 ns[key] = getattr(obj, key)
72 except AttributeError:
71 except AttributeError:
73 pass
72 pass
74 return ns
73 return ns
75
74
76 def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
75 def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
77 show_all=True):
76 show_all=True):
78 """Filter a namespace dictionary by name pattern and item type."""
77 """Filter a namespace dictionary by name pattern and item type."""
79 pattern = name_pattern.replace("*",".*").replace("?",".")
78 pattern = name_pattern.replace("*",".*").replace("?",".")
80 if ignore_case:
79 if ignore_case:
81 reg = re.compile(pattern+"$", re.I)
80 reg = re.compile(pattern+"$", re.I)
82 else:
81 else:
83 reg = re.compile(pattern+"$")
82 reg = re.compile(pattern+"$")
84
83
85 # Check each one matches regex; shouldn't be hidden; of correct type.
84 # Check each one matches regex; shouldn't be hidden; of correct type.
86 return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \
85 return dict((key,obj) for key, obj in ns.items() if reg.match(key) \
87 and show_hidden(key, show_all) \
86 and show_hidden(key, show_all) \
88 and is_type(obj, type_pattern) )
87 and is_type(obj, type_pattern) )
89
88
90 def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
89 def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
91 """Return dictionary of all objects in a namespace dictionary that match
90 """Return dictionary of all objects in a namespace dictionary that match
92 type_pattern and filter."""
91 type_pattern and filter."""
93 pattern_list=filter.split(".")
92 pattern_list=filter.split(".")
94 if len(pattern_list) == 1:
93 if len(pattern_list) == 1:
95 return filter_ns(namespace, name_pattern=pattern_list[0],
94 return filter_ns(namespace, name_pattern=pattern_list[0],
96 type_pattern=type_pattern,
95 type_pattern=type_pattern,
97 ignore_case=ignore_case, show_all=show_all)
96 ignore_case=ignore_case, show_all=show_all)
98 else:
97 else:
99 # This is where we can change if all objects should be searched or
98 # This is where we can change if all objects should be searched or
100 # only modules. Just change the type_pattern to module to search only
99 # only modules. Just change the type_pattern to module to search only
101 # modules
100 # modules
102 filtered = filter_ns(namespace, name_pattern=pattern_list[0],
101 filtered = filter_ns(namespace, name_pattern=pattern_list[0],
103 type_pattern="all",
102 type_pattern="all",
104 ignore_case=ignore_case, show_all=show_all)
103 ignore_case=ignore_case, show_all=show_all)
105 results = {}
104 results = {}
106 for name, obj in iteritems(filtered):
105 for name, obj in filtered.items():
107 ns = list_namespace(dict_dir(obj), type_pattern,
106 ns = list_namespace(dict_dir(obj), type_pattern,
108 ".".join(pattern_list[1:]),
107 ".".join(pattern_list[1:]),
109 ignore_case=ignore_case, show_all=show_all)
108 ignore_case=ignore_case, show_all=show_all)
110 for inner_name, inner_obj in iteritems(ns):
109 for inner_name, inner_obj in ns.items():
111 results["%s.%s"%(name,inner_name)] = inner_obj
110 results["%s.%s"%(name,inner_name)] = inner_obj
112 return results
111 return results
General Comments 0
You need to be logged in to leave comments. Login now