##// END OF EJS Templates
Fix docstring of `%reset`....
Antony Lee -
Show More
@@ -1,714 +1,714 b''
1 """Implementation of namespace-related magic functions.
1 """Implementation of namespace-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import gc
16 import gc
17 import re
17 import re
18 import sys
18 import sys
19
19
20 # Our own packages
20 # Our own packages
21 from IPython.core import page
21 from IPython.core import page
22 from IPython.core.error import StdinNotImplementedError, UsageError
22 from IPython.core.error import StdinNotImplementedError, UsageError
23 from IPython.core.magic import Magics, magics_class, line_magic
23 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.testing.skipdoctest import skip_doctest
24 from IPython.testing.skipdoctest import skip_doctest
25 from IPython.utils.encoding import DEFAULT_ENCODING
25 from IPython.utils.encoding import DEFAULT_ENCODING
26 from IPython.utils.openpy import read_py_file
26 from IPython.utils.openpy import read_py_file
27 from IPython.utils.path import get_py_filename
27 from IPython.utils.path import get_py_filename
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Magic implementation classes
30 # Magic implementation classes
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 @magics_class
33 @magics_class
34 class NamespaceMagics(Magics):
34 class NamespaceMagics(Magics):
35 """Magics to manage various aspects of the user's namespace.
35 """Magics to manage various aspects of the user's namespace.
36
36
37 These include listing variables, introspecting into them, etc.
37 These include listing variables, introspecting into them, etc.
38 """
38 """
39
39
40 @line_magic
40 @line_magic
41 def pinfo(self, parameter_s='', namespaces=None):
41 def pinfo(self, parameter_s='', namespaces=None):
42 """Provide detailed information about an object.
42 """Provide detailed information about an object.
43
43
44 '%pinfo object' is just a synonym for object? or ?object."""
44 '%pinfo object' is just a synonym for object? or ?object."""
45
45
46 #print 'pinfo par: <%s>' % parameter_s # dbg
46 #print 'pinfo par: <%s>' % parameter_s # dbg
47 # detail_level: 0 -> obj? , 1 -> obj??
47 # detail_level: 0 -> obj? , 1 -> obj??
48 detail_level = 0
48 detail_level = 0
49 # We need to detect if we got called as 'pinfo pinfo foo', which can
49 # We need to detect if we got called as 'pinfo pinfo foo', which can
50 # happen if the user types 'pinfo foo?' at the cmd line.
50 # happen if the user types 'pinfo foo?' at the cmd line.
51 pinfo,qmark1,oname,qmark2 = \
51 pinfo,qmark1,oname,qmark2 = \
52 re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
52 re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
53 if pinfo or qmark1 or qmark2:
53 if pinfo or qmark1 or qmark2:
54 detail_level = 1
54 detail_level = 1
55 if "*" in oname:
55 if "*" in oname:
56 self.psearch(oname)
56 self.psearch(oname)
57 else:
57 else:
58 self.shell._inspect('pinfo', oname, detail_level=detail_level,
58 self.shell._inspect('pinfo', oname, detail_level=detail_level,
59 namespaces=namespaces)
59 namespaces=namespaces)
60
60
61 @line_magic
61 @line_magic
62 def pinfo2(self, parameter_s='', namespaces=None):
62 def pinfo2(self, parameter_s='', namespaces=None):
63 """Provide extra detailed information about an object.
63 """Provide extra detailed information about an object.
64
64
65 '%pinfo2 object' is just a synonym for object?? or ??object."""
65 '%pinfo2 object' is just a synonym for object?? or ??object."""
66 self.shell._inspect('pinfo', parameter_s, detail_level=1,
66 self.shell._inspect('pinfo', parameter_s, detail_level=1,
67 namespaces=namespaces)
67 namespaces=namespaces)
68
68
69 @skip_doctest
69 @skip_doctest
70 @line_magic
70 @line_magic
71 def pdef(self, parameter_s='', namespaces=None):
71 def pdef(self, parameter_s='', namespaces=None):
72 """Print the call signature for any callable object.
72 """Print the call signature for any callable object.
73
73
74 If the object is a class, print the constructor information.
74 If the object is a class, print the constructor information.
75
75
76 Examples
76 Examples
77 --------
77 --------
78 ::
78 ::
79
79
80 In [3]: %pdef urllib.urlopen
80 In [3]: %pdef urllib.urlopen
81 urllib.urlopen(url, data=None, proxies=None)
81 urllib.urlopen(url, data=None, proxies=None)
82 """
82 """
83 self.shell._inspect('pdef',parameter_s, namespaces)
83 self.shell._inspect('pdef',parameter_s, namespaces)
84
84
85 @line_magic
85 @line_magic
86 def pdoc(self, parameter_s='', namespaces=None):
86 def pdoc(self, parameter_s='', namespaces=None):
87 """Print the docstring for an object.
87 """Print the docstring for an object.
88
88
89 If the given object is a class, it will print both the class and the
89 If the given object is a class, it will print both the class and the
90 constructor docstrings."""
90 constructor docstrings."""
91 self.shell._inspect('pdoc',parameter_s, namespaces)
91 self.shell._inspect('pdoc',parameter_s, namespaces)
92
92
93 @line_magic
93 @line_magic
94 def psource(self, parameter_s='', namespaces=None):
94 def psource(self, parameter_s='', namespaces=None):
95 """Print (or run through pager) the source code for an object."""
95 """Print (or run through pager) the source code for an object."""
96 if not parameter_s:
96 if not parameter_s:
97 raise UsageError('Missing object name.')
97 raise UsageError('Missing object name.')
98 self.shell._inspect('psource',parameter_s, namespaces)
98 self.shell._inspect('psource',parameter_s, namespaces)
99
99
100 @line_magic
100 @line_magic
101 def pfile(self, parameter_s='', namespaces=None):
101 def pfile(self, parameter_s='', namespaces=None):
102 """Print (or run through pager) the file where an object is defined.
102 """Print (or run through pager) the file where an object is defined.
103
103
104 The file opens at the line where the object definition begins. IPython
104 The file opens at the line where the object definition begins. IPython
105 will honor the environment variable PAGER if set, and otherwise will
105 will honor the environment variable PAGER if set, and otherwise will
106 do its best to print the file in a convenient form.
106 do its best to print the file in a convenient form.
107
107
108 If the given argument is not an object currently defined, IPython will
108 If the given argument is not an object currently defined, IPython will
109 try to interpret it as a filename (automatically adding a .py extension
109 try to interpret it as a filename (automatically adding a .py extension
110 if needed). You can thus use %pfile as a syntax highlighting code
110 if needed). You can thus use %pfile as a syntax highlighting code
111 viewer."""
111 viewer."""
112
112
113 # first interpret argument as an object name
113 # first interpret argument as an object name
114 out = self.shell._inspect('pfile',parameter_s, namespaces)
114 out = self.shell._inspect('pfile',parameter_s, namespaces)
115 # if not, try the input as a filename
115 # if not, try the input as a filename
116 if out == 'not found':
116 if out == 'not found':
117 try:
117 try:
118 filename = get_py_filename(parameter_s)
118 filename = get_py_filename(parameter_s)
119 except IOError as msg:
119 except IOError as msg:
120 print(msg)
120 print(msg)
121 return
121 return
122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123
123
124 @line_magic
124 @line_magic
125 def psearch(self, parameter_s=''):
125 def psearch(self, parameter_s=''):
126 """Search for object in namespaces by wildcard.
126 """Search for object in namespaces by wildcard.
127
127
128 %psearch [options] PATTERN [OBJECT TYPE]
128 %psearch [options] PATTERN [OBJECT TYPE]
129
129
130 Note: ? can be used as a synonym for %psearch, at the beginning or at
130 Note: ? can be used as a synonym for %psearch, at the beginning or at
131 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
131 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
132 rest of the command line must be unchanged (options come first), so
132 rest of the command line must be unchanged (options come first), so
133 for example the following forms are equivalent
133 for example the following forms are equivalent
134
134
135 %psearch -i a* function
135 %psearch -i a* function
136 -i a* function?
136 -i a* function?
137 ?-i a* function
137 ?-i a* function
138
138
139 Arguments:
139 Arguments:
140
140
141 PATTERN
141 PATTERN
142
142
143 where PATTERN is a string containing * as a wildcard similar to its
143 where PATTERN is a string containing * as a wildcard similar to its
144 use in a shell. The pattern is matched in all namespaces on the
144 use in a shell. The pattern is matched in all namespaces on the
145 search path. By default objects starting with a single _ are not
145 search path. By default objects starting with a single _ are not
146 matched, many IPython generated objects have a single
146 matched, many IPython generated objects have a single
147 underscore. The default is case insensitive matching. Matching is
147 underscore. The default is case insensitive matching. Matching is
148 also done on the attributes of objects and not only on the objects
148 also done on the attributes of objects and not only on the objects
149 in a module.
149 in a module.
150
150
151 [OBJECT TYPE]
151 [OBJECT TYPE]
152
152
153 Is the name of a python type from the types module. The name is
153 Is the name of a python type from the types module. The name is
154 given in lowercase without the ending type, ex. StringType is
154 given in lowercase without the ending type, ex. StringType is
155 written string. By adding a type here only objects matching the
155 written string. By adding a type here only objects matching the
156 given type are matched. Using all here makes the pattern match all
156 given type are matched. Using all here makes the pattern match all
157 types (this is the default).
157 types (this is the default).
158
158
159 Options:
159 Options:
160
160
161 -a: makes the pattern match even objects whose names start with a
161 -a: makes the pattern match even objects whose names start with a
162 single underscore. These names are normally omitted from the
162 single underscore. These names are normally omitted from the
163 search.
163 search.
164
164
165 -i/-c: make the pattern case insensitive/sensitive. If neither of
165 -i/-c: make the pattern case insensitive/sensitive. If neither of
166 these options are given, the default is read from your configuration
166 these options are given, the default is read from your configuration
167 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
167 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
168 If this option is not specified in your configuration file, IPython's
168 If this option is not specified in your configuration file, IPython's
169 internal default is to do a case sensitive search.
169 internal default is to do a case sensitive search.
170
170
171 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
171 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
172 specify can be searched in any of the following namespaces:
172 specify can be searched in any of the following namespaces:
173 'builtin', 'user', 'user_global','internal', 'alias', where
173 'builtin', 'user', 'user_global','internal', 'alias', where
174 'builtin' and 'user' are the search defaults. Note that you should
174 'builtin' and 'user' are the search defaults. Note that you should
175 not use quotes when specifying namespaces.
175 not use quotes when specifying namespaces.
176
176
177 -l: List all available object types for object matching. This function
177 -l: List all available object types for object matching. This function
178 can be used without arguments.
178 can be used without arguments.
179
179
180 'Builtin' contains the python module builtin, 'user' contains all
180 'Builtin' contains the python module builtin, 'user' contains all
181 user data, 'alias' only contain the shell aliases and no python
181 user data, 'alias' only contain the shell aliases and no python
182 objects, 'internal' contains objects used by IPython. The
182 objects, 'internal' contains objects used by IPython. The
183 'user_global' namespace is only used by embedded IPython instances,
183 'user_global' namespace is only used by embedded IPython instances,
184 and it contains module-level globals. You can add namespaces to the
184 and it contains module-level globals. You can add namespaces to the
185 search with -s or exclude them with -e (these options can be given
185 search with -s or exclude them with -e (these options can be given
186 more than once).
186 more than once).
187
187
188 Examples
188 Examples
189 --------
189 --------
190 ::
190 ::
191
191
192 %psearch a* -> objects beginning with an a
192 %psearch a* -> objects beginning with an a
193 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
193 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
194 %psearch a* function -> all functions beginning with an a
194 %psearch a* function -> all functions beginning with an a
195 %psearch re.e* -> objects beginning with an e in module re
195 %psearch re.e* -> objects beginning with an e in module re
196 %psearch r*.e* -> objects that start with e in modules starting in r
196 %psearch r*.e* -> objects that start with e in modules starting in r
197 %psearch r*.* string -> all strings in modules beginning with r
197 %psearch r*.* string -> all strings in modules beginning with r
198
198
199 Case sensitive search::
199 Case sensitive search::
200
200
201 %psearch -c a* list all object beginning with lower case a
201 %psearch -c a* list all object beginning with lower case a
202
202
203 Show objects beginning with a single _::
203 Show objects beginning with a single _::
204
204
205 %psearch -a _* list objects beginning with a single underscore
205 %psearch -a _* list objects beginning with a single underscore
206
206
207 List available objects::
207 List available objects::
208
208
209 %psearch -l list all available object types
209 %psearch -l list all available object types
210 """
210 """
211 try:
211 try:
212 parameter_s.encode('ascii')
212 parameter_s.encode('ascii')
213 except UnicodeEncodeError:
213 except UnicodeEncodeError:
214 print('Python identifiers can only contain ascii characters.')
214 print('Python identifiers can only contain ascii characters.')
215 return
215 return
216
216
217 # default namespaces to be searched
217 # default namespaces to be searched
218 def_search = ['user_local', 'user_global', 'builtin']
218 def_search = ['user_local', 'user_global', 'builtin']
219
219
220 # Process options/args
220 # Process options/args
221 opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True)
221 opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True)
222 opt = opts.get
222 opt = opts.get
223 shell = self.shell
223 shell = self.shell
224 psearch = shell.inspector.psearch
224 psearch = shell.inspector.psearch
225
225
226 # select list object types
226 # select list object types
227 list_types = False
227 list_types = False
228 if 'l' in opts:
228 if 'l' in opts:
229 list_types = True
229 list_types = True
230
230
231 # select case options
231 # select case options
232 if 'i' in opts:
232 if 'i' in opts:
233 ignore_case = True
233 ignore_case = True
234 elif 'c' in opts:
234 elif 'c' in opts:
235 ignore_case = False
235 ignore_case = False
236 else:
236 else:
237 ignore_case = not shell.wildcards_case_sensitive
237 ignore_case = not shell.wildcards_case_sensitive
238
238
239 # Build list of namespaces to search from user options
239 # Build list of namespaces to search from user options
240 def_search.extend(opt('s',[]))
240 def_search.extend(opt('s',[]))
241 ns_exclude = ns_exclude=opt('e',[])
241 ns_exclude = ns_exclude=opt('e',[])
242 ns_search = [nm for nm in def_search if nm not in ns_exclude]
242 ns_search = [nm for nm in def_search if nm not in ns_exclude]
243
243
244 # Call the actual search
244 # Call the actual search
245 try:
245 try:
246 psearch(args,shell.ns_table,ns_search,
246 psearch(args,shell.ns_table,ns_search,
247 show_all=opt('a'),ignore_case=ignore_case, list_types=list_types)
247 show_all=opt('a'),ignore_case=ignore_case, list_types=list_types)
248 except:
248 except:
249 shell.showtraceback()
249 shell.showtraceback()
250
250
251 @skip_doctest
251 @skip_doctest
252 @line_magic
252 @line_magic
253 def who_ls(self, parameter_s=''):
253 def who_ls(self, parameter_s=''):
254 """Return a sorted list of all interactive variables.
254 """Return a sorted list of all interactive variables.
255
255
256 If arguments are given, only variables of types matching these
256 If arguments are given, only variables of types matching these
257 arguments are returned.
257 arguments are returned.
258
258
259 Examples
259 Examples
260 --------
260 --------
261
261
262 Define two variables and list them with who_ls::
262 Define two variables and list them with who_ls::
263
263
264 In [1]: alpha = 123
264 In [1]: alpha = 123
265
265
266 In [2]: beta = 'test'
266 In [2]: beta = 'test'
267
267
268 In [3]: %who_ls
268 In [3]: %who_ls
269 Out[3]: ['alpha', 'beta']
269 Out[3]: ['alpha', 'beta']
270
270
271 In [4]: %who_ls int
271 In [4]: %who_ls int
272 Out[4]: ['alpha']
272 Out[4]: ['alpha']
273
273
274 In [5]: %who_ls str
274 In [5]: %who_ls str
275 Out[5]: ['beta']
275 Out[5]: ['beta']
276 """
276 """
277
277
278 user_ns = self.shell.user_ns
278 user_ns = self.shell.user_ns
279 user_ns_hidden = self.shell.user_ns_hidden
279 user_ns_hidden = self.shell.user_ns_hidden
280 nonmatching = object() # This can never be in user_ns
280 nonmatching = object() # This can never be in user_ns
281 out = [ i for i in user_ns
281 out = [ i for i in user_ns
282 if not i.startswith('_') \
282 if not i.startswith('_') \
283 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
283 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
284
284
285 typelist = parameter_s.split()
285 typelist = parameter_s.split()
286 if typelist:
286 if typelist:
287 typeset = set(typelist)
287 typeset = set(typelist)
288 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
288 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
289
289
290 out.sort()
290 out.sort()
291 return out
291 return out
292
292
293 @skip_doctest
293 @skip_doctest
294 @line_magic
294 @line_magic
295 def who(self, parameter_s=''):
295 def who(self, parameter_s=''):
296 """Print all interactive variables, with some minimal formatting.
296 """Print all interactive variables, with some minimal formatting.
297
297
298 If any arguments are given, only variables whose type matches one of
298 If any arguments are given, only variables whose type matches one of
299 these are printed. For example::
299 these are printed. For example::
300
300
301 %who function str
301 %who function str
302
302
303 will only list functions and strings, excluding all other types of
303 will only list functions and strings, excluding all other types of
304 variables. To find the proper type names, simply use type(var) at a
304 variables. To find the proper type names, simply use type(var) at a
305 command line to see how python prints type names. For example:
305 command line to see how python prints type names. For example:
306
306
307 ::
307 ::
308
308
309 In [1]: type('hello')\\
309 In [1]: type('hello')\\
310 Out[1]: <type 'str'>
310 Out[1]: <type 'str'>
311
311
312 indicates that the type name for strings is 'str'.
312 indicates that the type name for strings is 'str'.
313
313
314 ``%who`` always excludes executed names loaded through your configuration
314 ``%who`` always excludes executed names loaded through your configuration
315 file and things which are internal to IPython.
315 file and things which are internal to IPython.
316
316
317 This is deliberate, as typically you may load many modules and the
317 This is deliberate, as typically you may load many modules and the
318 purpose of %who is to show you only what you've manually defined.
318 purpose of %who is to show you only what you've manually defined.
319
319
320 Examples
320 Examples
321 --------
321 --------
322
322
323 Define two variables and list them with who::
323 Define two variables and list them with who::
324
324
325 In [1]: alpha = 123
325 In [1]: alpha = 123
326
326
327 In [2]: beta = 'test'
327 In [2]: beta = 'test'
328
328
329 In [3]: %who
329 In [3]: %who
330 alpha beta
330 alpha beta
331
331
332 In [4]: %who int
332 In [4]: %who int
333 alpha
333 alpha
334
334
335 In [5]: %who str
335 In [5]: %who str
336 beta
336 beta
337 """
337 """
338
338
339 varlist = self.who_ls(parameter_s)
339 varlist = self.who_ls(parameter_s)
340 if not varlist:
340 if not varlist:
341 if parameter_s:
341 if parameter_s:
342 print('No variables match your requested type.')
342 print('No variables match your requested type.')
343 else:
343 else:
344 print('Interactive namespace is empty.')
344 print('Interactive namespace is empty.')
345 return
345 return
346
346
347 # if we have variables, move on...
347 # if we have variables, move on...
348 count = 0
348 count = 0
349 for i in varlist:
349 for i in varlist:
350 print(i+'\t', end=' ')
350 print(i+'\t', end=' ')
351 count += 1
351 count += 1
352 if count > 8:
352 if count > 8:
353 count = 0
353 count = 0
354 print()
354 print()
355 print()
355 print()
356
356
357 @skip_doctest
357 @skip_doctest
358 @line_magic
358 @line_magic
359 def whos(self, parameter_s=''):
359 def whos(self, parameter_s=''):
360 """Like %who, but gives some extra information about each variable.
360 """Like %who, but gives some extra information about each variable.
361
361
362 The same type filtering of %who can be applied here.
362 The same type filtering of %who can be applied here.
363
363
364 For all variables, the type is printed. Additionally it prints:
364 For all variables, the type is printed. Additionally it prints:
365
365
366 - For {},[],(): their length.
366 - For {},[],(): their length.
367
367
368 - For numpy arrays, a summary with shape, number of
368 - For numpy arrays, a summary with shape, number of
369 elements, typecode and size in memory.
369 elements, typecode and size in memory.
370
370
371 - Everything else: a string representation, snipping their middle if
371 - Everything else: a string representation, snipping their middle if
372 too long.
372 too long.
373
373
374 Examples
374 Examples
375 --------
375 --------
376
376
377 Define two variables and list them with whos::
377 Define two variables and list them with whos::
378
378
379 In [1]: alpha = 123
379 In [1]: alpha = 123
380
380
381 In [2]: beta = 'test'
381 In [2]: beta = 'test'
382
382
383 In [3]: %whos
383 In [3]: %whos
384 Variable Type Data/Info
384 Variable Type Data/Info
385 --------------------------------
385 --------------------------------
386 alpha int 123
386 alpha int 123
387 beta str test
387 beta str test
388 """
388 """
389
389
390 varnames = self.who_ls(parameter_s)
390 varnames = self.who_ls(parameter_s)
391 if not varnames:
391 if not varnames:
392 if parameter_s:
392 if parameter_s:
393 print('No variables match your requested type.')
393 print('No variables match your requested type.')
394 else:
394 else:
395 print('Interactive namespace is empty.')
395 print('Interactive namespace is empty.')
396 return
396 return
397
397
398 # if we have variables, move on...
398 # if we have variables, move on...
399
399
400 # for these types, show len() instead of data:
400 # for these types, show len() instead of data:
401 seq_types = ['dict', 'list', 'tuple']
401 seq_types = ['dict', 'list', 'tuple']
402
402
403 # for numpy arrays, display summary info
403 # for numpy arrays, display summary info
404 ndarray_type = None
404 ndarray_type = None
405 if 'numpy' in sys.modules:
405 if 'numpy' in sys.modules:
406 try:
406 try:
407 from numpy import ndarray
407 from numpy import ndarray
408 except ImportError:
408 except ImportError:
409 pass
409 pass
410 else:
410 else:
411 ndarray_type = ndarray.__name__
411 ndarray_type = ndarray.__name__
412
412
413 # Find all variable names and types so we can figure out column sizes
413 # Find all variable names and types so we can figure out column sizes
414
414
415 # some types are well known and can be shorter
415 # some types are well known and can be shorter
416 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
416 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
417 def type_name(v):
417 def type_name(v):
418 tn = type(v).__name__
418 tn = type(v).__name__
419 return abbrevs.get(tn,tn)
419 return abbrevs.get(tn,tn)
420
420
421 varlist = [self.shell.user_ns[n] for n in varnames]
421 varlist = [self.shell.user_ns[n] for n in varnames]
422
422
423 typelist = []
423 typelist = []
424 for vv in varlist:
424 for vv in varlist:
425 tt = type_name(vv)
425 tt = type_name(vv)
426
426
427 if tt=='instance':
427 if tt=='instance':
428 typelist.append( abbrevs.get(str(vv.__class__),
428 typelist.append( abbrevs.get(str(vv.__class__),
429 str(vv.__class__)))
429 str(vv.__class__)))
430 else:
430 else:
431 typelist.append(tt)
431 typelist.append(tt)
432
432
433 # column labels and # of spaces as separator
433 # column labels and # of spaces as separator
434 varlabel = 'Variable'
434 varlabel = 'Variable'
435 typelabel = 'Type'
435 typelabel = 'Type'
436 datalabel = 'Data/Info'
436 datalabel = 'Data/Info'
437 colsep = 3
437 colsep = 3
438 # variable format strings
438 # variable format strings
439 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
439 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
440 aformat = "%s: %s elems, type `%s`, %s bytes"
440 aformat = "%s: %s elems, type `%s`, %s bytes"
441 # find the size of the columns to format the output nicely
441 # find the size of the columns to format the output nicely
442 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
442 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
443 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
443 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
444 # table header
444 # table header
445 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
445 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
446 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
446 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
447 # and the table itself
447 # and the table itself
448 kb = 1024
448 kb = 1024
449 Mb = 1048576 # kb**2
449 Mb = 1048576 # kb**2
450 for vname,var,vtype in zip(varnames,varlist,typelist):
450 for vname,var,vtype in zip(varnames,varlist,typelist):
451 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
451 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
452 if vtype in seq_types:
452 if vtype in seq_types:
453 print("n="+str(len(var)))
453 print("n="+str(len(var)))
454 elif vtype == ndarray_type:
454 elif vtype == ndarray_type:
455 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
455 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
456 if vtype==ndarray_type:
456 if vtype==ndarray_type:
457 # numpy
457 # numpy
458 vsize = var.size
458 vsize = var.size
459 vbytes = vsize*var.itemsize
459 vbytes = vsize*var.itemsize
460 vdtype = var.dtype
460 vdtype = var.dtype
461
461
462 if vbytes < 100000:
462 if vbytes < 100000:
463 print(aformat % (vshape, vsize, vdtype, vbytes))
463 print(aformat % (vshape, vsize, vdtype, vbytes))
464 else:
464 else:
465 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
465 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
466 if vbytes < Mb:
466 if vbytes < Mb:
467 print('(%s kb)' % (vbytes/kb,))
467 print('(%s kb)' % (vbytes/kb,))
468 else:
468 else:
469 print('(%s Mb)' % (vbytes/Mb,))
469 print('(%s Mb)' % (vbytes/Mb,))
470 else:
470 else:
471 try:
471 try:
472 vstr = str(var)
472 vstr = str(var)
473 except UnicodeEncodeError:
473 except UnicodeEncodeError:
474 vstr = var.encode(DEFAULT_ENCODING,
474 vstr = var.encode(DEFAULT_ENCODING,
475 'backslashreplace')
475 'backslashreplace')
476 except:
476 except:
477 vstr = "<object with id %d (str() failed)>" % id(var)
477 vstr = "<object with id %d (str() failed)>" % id(var)
478 vstr = vstr.replace('\n', '\\n')
478 vstr = vstr.replace('\n', '\\n')
479 if len(vstr) < 50:
479 if len(vstr) < 50:
480 print(vstr)
480 print(vstr)
481 else:
481 else:
482 print(vstr[:25] + "<...>" + vstr[-25:])
482 print(vstr[:25] + "<...>" + vstr[-25:])
483
483
484 @line_magic
484 @line_magic
485 def reset(self, parameter_s=''):
485 def reset(self, parameter_s=''):
486 """Resets the namespace by removing all names defined by the user, if
486 """Resets the namespace by removing all names defined by the user, if
487 called without arguments, or by removing some types of objects, such
487 called without arguments, or by removing some types of objects, such
488 as everything currently in IPython's In[] and Out[] containers (see
488 as everything currently in IPython's In[] and Out[] containers (see
489 the parameters for details).
489 the parameters for details).
490
490
491 Parameters
491 Parameters
492 ----------
492 ----------
493 -f : force reset without asking for confirmation.
493 -f : force reset without asking for confirmation.
494
494
495 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
495 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
496 References to objects may be kept. By default (without this option),
496 References to objects may be kept. By default (without this option),
497 we do a 'hard' reset, giving you a new session and removing all
497 we do a 'hard' reset, giving you a new session and removing all
498 references to objects from the current session.
498 references to objects from the current session.
499
499
500 in : reset input history
500 in : reset input history
501
501
502 out : reset output history
502 out : reset output history
503
503
504 dhist : reset directory history
504 dhist : reset directory history
505
505
506 array : reset only variables that are NumPy arrays
506 array : reset only variables that are NumPy arrays
507
507
508 See Also
508 See Also
509 --------
509 --------
510 reset_selective : invoked as ``%reset_selective``
510 reset_selective : invoked as ``%reset_selective``
511
511
512 Examples
512 Examples
513 --------
513 --------
514 ::
514 ::
515
515
516 In [6]: a = 1
516 In [6]: a = 1
517
517
518 In [7]: a
518 In [7]: a
519 Out[7]: 1
519 Out[7]: 1
520
520
521 In [8]: 'a' in _ip.user_ns
521 In [8]: 'a' in get_ipython().user_ns
522 Out[8]: True
522 Out[8]: True
523
523
524 In [9]: %reset -f
524 In [9]: %reset -f
525
525
526 In [1]: 'a' in _ip.user_ns
526 In [1]: 'a' in get_ipython().user_ns
527 Out[1]: False
527 Out[1]: False
528
528
529 In [2]: %reset -f in
529 In [2]: %reset -f in
530 Flushing input history
530 Flushing input history
531
531
532 In [3]: %reset -f dhist in
532 In [3]: %reset -f dhist in
533 Flushing directory history
533 Flushing directory history
534 Flushing input history
534 Flushing input history
535
535
536 Notes
536 Notes
537 -----
537 -----
538 Calling this magic from clients that do not implement standard input,
538 Calling this magic from clients that do not implement standard input,
539 such as the ipython notebook interface, will reset the namespace
539 such as the ipython notebook interface, will reset the namespace
540 without confirmation.
540 without confirmation.
541 """
541 """
542 opts, args = self.parse_options(parameter_s,'sf', mode='list')
542 opts, args = self.parse_options(parameter_s,'sf', mode='list')
543 if 'f' in opts:
543 if 'f' in opts:
544 ans = True
544 ans = True
545 else:
545 else:
546 try:
546 try:
547 ans = self.shell.ask_yes_no(
547 ans = self.shell.ask_yes_no(
548 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
548 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
549 default='n')
549 default='n')
550 except StdinNotImplementedError:
550 except StdinNotImplementedError:
551 ans = True
551 ans = True
552 if not ans:
552 if not ans:
553 print('Nothing done.')
553 print('Nothing done.')
554 return
554 return
555
555
556 if 's' in opts: # Soft reset
556 if 's' in opts: # Soft reset
557 user_ns = self.shell.user_ns
557 user_ns = self.shell.user_ns
558 for i in self.who_ls():
558 for i in self.who_ls():
559 del(user_ns[i])
559 del(user_ns[i])
560 elif len(args) == 0: # Hard reset
560 elif len(args) == 0: # Hard reset
561 self.shell.reset(new_session = False)
561 self.shell.reset(new_session = False)
562
562
563 # reset in/out/dhist/array: previously extensinions/clearcmd.py
563 # reset in/out/dhist/array: previously extensinions/clearcmd.py
564 ip = self.shell
564 ip = self.shell
565 user_ns = self.shell.user_ns # local lookup, heavily used
565 user_ns = self.shell.user_ns # local lookup, heavily used
566
566
567 for target in args:
567 for target in args:
568 target = target.lower() # make matches case insensitive
568 target = target.lower() # make matches case insensitive
569 if target == 'out':
569 if target == 'out':
570 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
570 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
571 self.shell.displayhook.flush()
571 self.shell.displayhook.flush()
572
572
573 elif target == 'in':
573 elif target == 'in':
574 print("Flushing input history")
574 print("Flushing input history")
575 pc = self.shell.displayhook.prompt_count + 1
575 pc = self.shell.displayhook.prompt_count + 1
576 for n in range(1, pc):
576 for n in range(1, pc):
577 key = '_i'+repr(n)
577 key = '_i'+repr(n)
578 user_ns.pop(key,None)
578 user_ns.pop(key,None)
579 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
579 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
580 hm = ip.history_manager
580 hm = ip.history_manager
581 # don't delete these, as %save and %macro depending on the
581 # don't delete these, as %save and %macro depending on the
582 # length of these lists to be preserved
582 # length of these lists to be preserved
583 hm.input_hist_parsed[:] = [''] * pc
583 hm.input_hist_parsed[:] = [''] * pc
584 hm.input_hist_raw[:] = [''] * pc
584 hm.input_hist_raw[:] = [''] * pc
585 # hm has internal machinery for _i,_ii,_iii, clear it out
585 # hm has internal machinery for _i,_ii,_iii, clear it out
586 hm._i = hm._ii = hm._iii = hm._i00 = u''
586 hm._i = hm._ii = hm._iii = hm._i00 = u''
587
587
588 elif target == 'array':
588 elif target == 'array':
589 # Support cleaning up numpy arrays
589 # Support cleaning up numpy arrays
590 try:
590 try:
591 from numpy import ndarray
591 from numpy import ndarray
592 # This must be done with items and not iteritems because
592 # This must be done with items and not iteritems because
593 # we're going to modify the dict in-place.
593 # we're going to modify the dict in-place.
594 for x,val in list(user_ns.items()):
594 for x,val in list(user_ns.items()):
595 if isinstance(val,ndarray):
595 if isinstance(val,ndarray):
596 del user_ns[x]
596 del user_ns[x]
597 except ImportError:
597 except ImportError:
598 print("reset array only works if Numpy is available.")
598 print("reset array only works if Numpy is available.")
599
599
600 elif target == 'dhist':
600 elif target == 'dhist':
601 print("Flushing directory history")
601 print("Flushing directory history")
602 del user_ns['_dh'][:]
602 del user_ns['_dh'][:]
603
603
604 else:
604 else:
605 print("Don't know how to reset ", end=' ')
605 print("Don't know how to reset ", end=' ')
606 print(target + ", please run `%reset?` for details")
606 print(target + ", please run `%reset?` for details")
607
607
608 gc.collect()
608 gc.collect()
609
609
610 @line_magic
610 @line_magic
611 def reset_selective(self, parameter_s=''):
611 def reset_selective(self, parameter_s=''):
612 """Resets the namespace by removing names defined by the user.
612 """Resets the namespace by removing names defined by the user.
613
613
614 Input/Output history are left around in case you need them.
614 Input/Output history are left around in case you need them.
615
615
616 %reset_selective [-f] regex
616 %reset_selective [-f] regex
617
617
618 No action is taken if regex is not included
618 No action is taken if regex is not included
619
619
620 Options
620 Options
621 -f : force reset without asking for confirmation.
621 -f : force reset without asking for confirmation.
622
622
623 See Also
623 See Also
624 --------
624 --------
625 reset : invoked as ``%reset``
625 reset : invoked as ``%reset``
626
626
627 Examples
627 Examples
628 --------
628 --------
629
629
630 We first fully reset the namespace so your output looks identical to
630 We first fully reset the namespace so your output looks identical to
631 this example for pedagogical reasons; in practice you do not need a
631 this example for pedagogical reasons; in practice you do not need a
632 full reset::
632 full reset::
633
633
634 In [1]: %reset -f
634 In [1]: %reset -f
635
635
636 Now, with a clean namespace we can make a few variables and use
636 Now, with a clean namespace we can make a few variables and use
637 ``%reset_selective`` to only delete names that match our regexp::
637 ``%reset_selective`` to only delete names that match our regexp::
638
638
639 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
639 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
640
640
641 In [3]: who_ls
641 In [3]: who_ls
642 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
642 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
643
643
644 In [4]: %reset_selective -f b[2-3]m
644 In [4]: %reset_selective -f b[2-3]m
645
645
646 In [5]: who_ls
646 In [5]: who_ls
647 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
647 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
648
648
649 In [6]: %reset_selective -f d
649 In [6]: %reset_selective -f d
650
650
651 In [7]: who_ls
651 In [7]: who_ls
652 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
652 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
653
653
654 In [8]: %reset_selective -f c
654 In [8]: %reset_selective -f c
655
655
656 In [9]: who_ls
656 In [9]: who_ls
657 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
657 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
658
658
659 In [10]: %reset_selective -f b
659 In [10]: %reset_selective -f b
660
660
661 In [11]: who_ls
661 In [11]: who_ls
662 Out[11]: ['a']
662 Out[11]: ['a']
663
663
664 Notes
664 Notes
665 -----
665 -----
666 Calling this magic from clients that do not implement standard input,
666 Calling this magic from clients that do not implement standard input,
667 such as the ipython notebook interface, will reset the namespace
667 such as the ipython notebook interface, will reset the namespace
668 without confirmation.
668 without confirmation.
669 """
669 """
670
670
671 opts, regex = self.parse_options(parameter_s,'f')
671 opts, regex = self.parse_options(parameter_s,'f')
672
672
673 if 'f' in opts:
673 if 'f' in opts:
674 ans = True
674 ans = True
675 else:
675 else:
676 try:
676 try:
677 ans = self.shell.ask_yes_no(
677 ans = self.shell.ask_yes_no(
678 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
678 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
679 default='n')
679 default='n')
680 except StdinNotImplementedError:
680 except StdinNotImplementedError:
681 ans = True
681 ans = True
682 if not ans:
682 if not ans:
683 print('Nothing done.')
683 print('Nothing done.')
684 return
684 return
685 user_ns = self.shell.user_ns
685 user_ns = self.shell.user_ns
686 if not regex:
686 if not regex:
687 print('No regex pattern specified. Nothing done.')
687 print('No regex pattern specified. Nothing done.')
688 return
688 return
689 else:
689 else:
690 try:
690 try:
691 m = re.compile(regex)
691 m = re.compile(regex)
692 except TypeError:
692 except TypeError:
693 raise TypeError('regex must be a string or compiled pattern')
693 raise TypeError('regex must be a string or compiled pattern')
694 for i in self.who_ls():
694 for i in self.who_ls():
695 if m.search(i):
695 if m.search(i):
696 del(user_ns[i])
696 del(user_ns[i])
697
697
698 @line_magic
698 @line_magic
699 def xdel(self, parameter_s=''):
699 def xdel(self, parameter_s=''):
700 """Delete a variable, trying to clear it from anywhere that
700 """Delete a variable, trying to clear it from anywhere that
701 IPython's machinery has references to it. By default, this uses
701 IPython's machinery has references to it. By default, this uses
702 the identity of the named object in the user namespace to remove
702 the identity of the named object in the user namespace to remove
703 references held under other names. The object is also removed
703 references held under other names. The object is also removed
704 from the output history.
704 from the output history.
705
705
706 Options
706 Options
707 -n : Delete the specified name from all namespaces, without
707 -n : Delete the specified name from all namespaces, without
708 checking their identity.
708 checking their identity.
709 """
709 """
710 opts, varname = self.parse_options(parameter_s,'n')
710 opts, varname = self.parse_options(parameter_s,'n')
711 try:
711 try:
712 self.shell.del_var(varname, ('n' in opts))
712 self.shell.del_var(varname, ('n' in opts))
713 except (NameError, ValueError) as e:
713 except (NameError, ValueError) as e:
714 print(type(e).__name__ +": "+ str(e))
714 print(type(e).__name__ +": "+ str(e))
General Comments 0
You need to be logged in to leave comments. Login now