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