##// END OF EJS Templates
Explicitly close file in get_encoding
Thomas Kluyver -
Show More
@@ -1,877 +1,877 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 __all__ = ['Inspector','InspectColors']
18 __all__ = ['Inspector','InspectColors']
19
19
20 # stdlib modules
20 # stdlib modules
21 import inspect
21 import inspect
22 import linecache
22 import linecache
23 import os
23 import os
24 import types
24 import types
25 import io as stdlib_io
25 import io as stdlib_io
26
26
27 try:
27 try:
28 from itertools import izip_longest
28 from itertools import izip_longest
29 except ImportError:
29 except ImportError:
30 from itertools import zip_longest as izip_longest
30 from itertools import zip_longest as izip_longest
31
31
32 # IPython's own
32 # IPython's own
33 from IPython.core import page
33 from IPython.core import page
34 from IPython.testing.skipdoctest import skip_doctest_py3
34 from IPython.testing.skipdoctest import skip_doctest_py3
35 from IPython.utils import PyColorize
35 from IPython.utils import PyColorize
36 from IPython.utils import io
36 from IPython.utils import io
37 from IPython.utils import openpy
37 from IPython.utils import openpy
38 from IPython.utils import py3compat
38 from IPython.utils import py3compat
39 from IPython.utils.dir2 import safe_hasattr
39 from IPython.utils.dir2 import safe_hasattr
40 from IPython.utils.text import indent
40 from IPython.utils.text import indent
41 from IPython.utils.wildcard import list_namespace
41 from IPython.utils.wildcard import list_namespace
42 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
42 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
43 from IPython.utils.py3compat import cast_unicode, string_types, PY3
43 from IPython.utils.py3compat import cast_unicode, string_types, PY3
44
44
45 # builtin docstrings to ignore
45 # builtin docstrings to ignore
46 _func_call_docstring = types.FunctionType.__call__.__doc__
46 _func_call_docstring = types.FunctionType.__call__.__doc__
47 _object_init_docstring = object.__init__.__doc__
47 _object_init_docstring = object.__init__.__doc__
48 _builtin_type_docstrings = {
48 _builtin_type_docstrings = {
49 t.__doc__ for t in (types.ModuleType, types.MethodType, types.FunctionType)
49 t.__doc__ for t in (types.ModuleType, types.MethodType, types.FunctionType)
50 }
50 }
51
51
52 _builtin_func_type = type(all)
52 _builtin_func_type = type(all)
53 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
53 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
54 #****************************************************************************
54 #****************************************************************************
55 # Builtin color schemes
55 # Builtin color schemes
56
56
57 Colors = TermColors # just a shorthand
57 Colors = TermColors # just a shorthand
58
58
59 # Build a few color schemes
59 # Build a few color schemes
60 NoColor = ColorScheme(
60 NoColor = ColorScheme(
61 'NoColor',{
61 'NoColor',{
62 'header' : Colors.NoColor,
62 'header' : Colors.NoColor,
63 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
63 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
64 } )
64 } )
65
65
66 LinuxColors = ColorScheme(
66 LinuxColors = ColorScheme(
67 'Linux',{
67 'Linux',{
68 'header' : Colors.LightRed,
68 'header' : Colors.LightRed,
69 'normal' : Colors.Normal # color off (usu. Colors.Normal)
69 'normal' : Colors.Normal # color off (usu. Colors.Normal)
70 } )
70 } )
71
71
72 LightBGColors = ColorScheme(
72 LightBGColors = ColorScheme(
73 'LightBG',{
73 'LightBG',{
74 'header' : Colors.Red,
74 'header' : Colors.Red,
75 'normal' : Colors.Normal # color off (usu. Colors.Normal)
75 'normal' : Colors.Normal # color off (usu. Colors.Normal)
76 } )
76 } )
77
77
78 # Build table of color schemes (needed by the parser)
78 # Build table of color schemes (needed by the parser)
79 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
79 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
80 'Linux')
80 'Linux')
81
81
82 #****************************************************************************
82 #****************************************************************************
83 # Auxiliary functions and objects
83 # Auxiliary functions and objects
84
84
85 # See the messaging spec for the definition of all these fields. This list
85 # See the messaging spec for the definition of all these fields. This list
86 # effectively defines the order of display
86 # effectively defines the order of display
87 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
87 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
88 'length', 'file', 'definition', 'docstring', 'source',
88 'length', 'file', 'definition', 'docstring', 'source',
89 'init_definition', 'class_docstring', 'init_docstring',
89 'init_definition', 'class_docstring', 'init_docstring',
90 'call_def', 'call_docstring',
90 'call_def', 'call_docstring',
91 # These won't be printed but will be used to determine how to
91 # These won't be printed but will be used to determine how to
92 # format the object
92 # format the object
93 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
93 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
94 ]
94 ]
95
95
96
96
97 def object_info(**kw):
97 def object_info(**kw):
98 """Make an object info dict with all fields present."""
98 """Make an object info dict with all fields present."""
99 infodict = dict(izip_longest(info_fields, [None]))
99 infodict = dict(izip_longest(info_fields, [None]))
100 infodict.update(kw)
100 infodict.update(kw)
101 return infodict
101 return infodict
102
102
103
103
104 def get_encoding(obj):
104 def get_encoding(obj):
105 """Get encoding for python source file defining obj
105 """Get encoding for python source file defining obj
106
106
107 Returns None if obj is not defined in a sourcefile.
107 Returns None if obj is not defined in a sourcefile.
108 """
108 """
109 ofile = find_file(obj)
109 ofile = find_file(obj)
110 # run contents of file through pager starting at line where the object
110 # run contents of file through pager starting at line where the object
111 # is defined, as long as the file isn't binary and is actually on the
111 # is defined, as long as the file isn't binary and is actually on the
112 # filesystem.
112 # filesystem.
113 if ofile is None:
113 if ofile is None:
114 return None
114 return None
115 elif ofile.endswith(('.so', '.dll', '.pyd')):
115 elif ofile.endswith(('.so', '.dll', '.pyd')):
116 return None
116 return None
117 elif not os.path.isfile(ofile):
117 elif not os.path.isfile(ofile):
118 return None
118 return None
119 else:
119 else:
120 # Print only text files, not extension binaries. Note that
120 # Print only text files, not extension binaries. Note that
121 # getsourcelines returns lineno with 1-offset and page() uses
121 # getsourcelines returns lineno with 1-offset and page() uses
122 # 0-offset, so we must adjust.
122 # 0-offset, so we must adjust.
123 buffer = stdlib_io.open(ofile, 'rb') # Tweaked to use io.open for Python 2
123 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
124 encoding, lines = openpy.detect_encoding(buffer.readline)
124 encoding, lines = openpy.detect_encoding(buffer.readline)
125 return encoding
125 return encoding
126
126
127 def getdoc(obj):
127 def getdoc(obj):
128 """Stable wrapper around inspect.getdoc.
128 """Stable wrapper around inspect.getdoc.
129
129
130 This can't crash because of attribute problems.
130 This can't crash because of attribute problems.
131
131
132 It also attempts to call a getdoc() method on the given object. This
132 It also attempts to call a getdoc() method on the given object. This
133 allows objects which provide their docstrings via non-standard mechanisms
133 allows objects which provide their docstrings via non-standard mechanisms
134 (like Pyro proxies) to still be inspected by ipython's ? system."""
134 (like Pyro proxies) to still be inspected by ipython's ? system."""
135 # Allow objects to offer customized documentation via a getdoc method:
135 # Allow objects to offer customized documentation via a getdoc method:
136 try:
136 try:
137 ds = obj.getdoc()
137 ds = obj.getdoc()
138 except Exception:
138 except Exception:
139 pass
139 pass
140 else:
140 else:
141 # if we get extra info, we add it to the normal docstring.
141 # if we get extra info, we add it to the normal docstring.
142 if isinstance(ds, string_types):
142 if isinstance(ds, string_types):
143 return inspect.cleandoc(ds)
143 return inspect.cleandoc(ds)
144
144
145 try:
145 try:
146 docstr = inspect.getdoc(obj)
146 docstr = inspect.getdoc(obj)
147 encoding = get_encoding(obj)
147 encoding = get_encoding(obj)
148 return py3compat.cast_unicode(docstr, encoding=encoding)
148 return py3compat.cast_unicode(docstr, encoding=encoding)
149 except Exception:
149 except Exception:
150 # Harden against an inspect failure, which can occur with
150 # Harden against an inspect failure, which can occur with
151 # SWIG-wrapped extensions.
151 # SWIG-wrapped extensions.
152 raise
152 raise
153 return None
153 return None
154
154
155
155
156 def getsource(obj,is_binary=False):
156 def getsource(obj,is_binary=False):
157 """Wrapper around inspect.getsource.
157 """Wrapper around inspect.getsource.
158
158
159 This can be modified by other projects to provide customized source
159 This can be modified by other projects to provide customized source
160 extraction.
160 extraction.
161
161
162 Inputs:
162 Inputs:
163
163
164 - obj: an object whose source code we will attempt to extract.
164 - obj: an object whose source code we will attempt to extract.
165
165
166 Optional inputs:
166 Optional inputs:
167
167
168 - is_binary: whether the object is known to come from a binary source.
168 - is_binary: whether the object is known to come from a binary source.
169 This implementation will skip returning any output for binary objects, but
169 This implementation will skip returning any output for binary objects, but
170 custom extractors may know how to meaningfully process them."""
170 custom extractors may know how to meaningfully process them."""
171
171
172 if is_binary:
172 if is_binary:
173 return None
173 return None
174 else:
174 else:
175 # get source if obj was decorated with @decorator
175 # get source if obj was decorated with @decorator
176 if hasattr(obj,"__wrapped__"):
176 if hasattr(obj,"__wrapped__"):
177 obj = obj.__wrapped__
177 obj = obj.__wrapped__
178 try:
178 try:
179 src = inspect.getsource(obj)
179 src = inspect.getsource(obj)
180 except TypeError:
180 except TypeError:
181 if hasattr(obj,'__class__'):
181 if hasattr(obj,'__class__'):
182 src = inspect.getsource(obj.__class__)
182 src = inspect.getsource(obj.__class__)
183 encoding = get_encoding(obj)
183 encoding = get_encoding(obj)
184 return cast_unicode(src, encoding=encoding)
184 return cast_unicode(src, encoding=encoding)
185
185
186
186
187 def is_simple_callable(obj):
187 def is_simple_callable(obj):
188 """True if obj is a function ()"""
188 """True if obj is a function ()"""
189 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
189 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
190 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
190 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
191
191
192
192
193 def getargspec(obj):
193 def getargspec(obj):
194 """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
194 """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
195 :func:inspect.getargspec` on Python 2.
195 :func:inspect.getargspec` on Python 2.
196
196
197 In addition to functions and methods, this can also handle objects with a
197 In addition to functions and methods, this can also handle objects with a
198 ``__call__`` attribute.
198 ``__call__`` attribute.
199 """
199 """
200 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
200 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
201 obj = obj.__call__
201 obj = obj.__call__
202
202
203 return inspect.getfullargspec(obj) if PY3 else inspect.getargspec(obj)
203 return inspect.getfullargspec(obj) if PY3 else inspect.getargspec(obj)
204
204
205
205
206 def format_argspec(argspec):
206 def format_argspec(argspec):
207 """Format argspect, convenience wrapper around inspect's.
207 """Format argspect, convenience wrapper around inspect's.
208
208
209 This takes a dict instead of ordered arguments and calls
209 This takes a dict instead of ordered arguments and calls
210 inspect.format_argspec with the arguments in the necessary order.
210 inspect.format_argspec with the arguments in the necessary order.
211 """
211 """
212 return inspect.formatargspec(argspec['args'], argspec['varargs'],
212 return inspect.formatargspec(argspec['args'], argspec['varargs'],
213 argspec['varkw'], argspec['defaults'])
213 argspec['varkw'], argspec['defaults'])
214
214
215
215
216 def call_tip(oinfo, format_call=True):
216 def call_tip(oinfo, format_call=True):
217 """Extract call tip data from an oinfo dict.
217 """Extract call tip data from an oinfo dict.
218
218
219 Parameters
219 Parameters
220 ----------
220 ----------
221 oinfo : dict
221 oinfo : dict
222
222
223 format_call : bool, optional
223 format_call : bool, optional
224 If True, the call line is formatted and returned as a string. If not, a
224 If True, the call line is formatted and returned as a string. If not, a
225 tuple of (name, argspec) is returned.
225 tuple of (name, argspec) is returned.
226
226
227 Returns
227 Returns
228 -------
228 -------
229 call_info : None, str or (str, dict) tuple.
229 call_info : None, str or (str, dict) tuple.
230 When format_call is True, the whole call information is formattted as a
230 When format_call is True, the whole call information is formattted as a
231 single string. Otherwise, the object's name and its argspec dict are
231 single string. Otherwise, the object's name and its argspec dict are
232 returned. If no call information is available, None is returned.
232 returned. If no call information is available, None is returned.
233
233
234 docstring : str or None
234 docstring : str or None
235 The most relevant docstring for calling purposes is returned, if
235 The most relevant docstring for calling purposes is returned, if
236 available. The priority is: call docstring for callable instances, then
236 available. The priority is: call docstring for callable instances, then
237 constructor docstring for classes, then main object's docstring otherwise
237 constructor docstring for classes, then main object's docstring otherwise
238 (regular functions).
238 (regular functions).
239 """
239 """
240 # Get call definition
240 # Get call definition
241 argspec = oinfo.get('argspec')
241 argspec = oinfo.get('argspec')
242 if argspec is None:
242 if argspec is None:
243 call_line = None
243 call_line = None
244 else:
244 else:
245 # Callable objects will have 'self' as their first argument, prune
245 # Callable objects will have 'self' as their first argument, prune
246 # it out if it's there for clarity (since users do *not* pass an
246 # it out if it's there for clarity (since users do *not* pass an
247 # extra first argument explicitly).
247 # extra first argument explicitly).
248 try:
248 try:
249 has_self = argspec['args'][0] == 'self'
249 has_self = argspec['args'][0] == 'self'
250 except (KeyError, IndexError):
250 except (KeyError, IndexError):
251 pass
251 pass
252 else:
252 else:
253 if has_self:
253 if has_self:
254 argspec['args'] = argspec['args'][1:]
254 argspec['args'] = argspec['args'][1:]
255
255
256 call_line = oinfo['name']+format_argspec(argspec)
256 call_line = oinfo['name']+format_argspec(argspec)
257
257
258 # Now get docstring.
258 # Now get docstring.
259 # The priority is: call docstring, constructor docstring, main one.
259 # The priority is: call docstring, constructor docstring, main one.
260 doc = oinfo.get('call_docstring')
260 doc = oinfo.get('call_docstring')
261 if doc is None:
261 if doc is None:
262 doc = oinfo.get('init_docstring')
262 doc = oinfo.get('init_docstring')
263 if doc is None:
263 if doc is None:
264 doc = oinfo.get('docstring','')
264 doc = oinfo.get('docstring','')
265
265
266 return call_line, doc
266 return call_line, doc
267
267
268
268
269 def find_file(obj):
269 def find_file(obj):
270 """Find the absolute path to the file where an object was defined.
270 """Find the absolute path to the file where an object was defined.
271
271
272 This is essentially a robust wrapper around `inspect.getabsfile`.
272 This is essentially a robust wrapper around `inspect.getabsfile`.
273
273
274 Returns None if no file can be found.
274 Returns None if no file can be found.
275
275
276 Parameters
276 Parameters
277 ----------
277 ----------
278 obj : any Python object
278 obj : any Python object
279
279
280 Returns
280 Returns
281 -------
281 -------
282 fname : str
282 fname : str
283 The absolute path to the file where the object was defined.
283 The absolute path to the file where the object was defined.
284 """
284 """
285 # get source if obj was decorated with @decorator
285 # get source if obj was decorated with @decorator
286 if safe_hasattr(obj, '__wrapped__'):
286 if safe_hasattr(obj, '__wrapped__'):
287 obj = obj.__wrapped__
287 obj = obj.__wrapped__
288
288
289 fname = None
289 fname = None
290 try:
290 try:
291 fname = inspect.getabsfile(obj)
291 fname = inspect.getabsfile(obj)
292 except TypeError:
292 except TypeError:
293 # For an instance, the file that matters is where its class was
293 # For an instance, the file that matters is where its class was
294 # declared.
294 # declared.
295 if hasattr(obj, '__class__'):
295 if hasattr(obj, '__class__'):
296 try:
296 try:
297 fname = inspect.getabsfile(obj.__class__)
297 fname = inspect.getabsfile(obj.__class__)
298 except TypeError:
298 except TypeError:
299 # Can happen for builtins
299 # Can happen for builtins
300 pass
300 pass
301 except:
301 except:
302 pass
302 pass
303 return cast_unicode(fname)
303 return cast_unicode(fname)
304
304
305
305
306 def find_source_lines(obj):
306 def find_source_lines(obj):
307 """Find the line number in a file where an object was defined.
307 """Find the line number in a file where an object was defined.
308
308
309 This is essentially a robust wrapper around `inspect.getsourcelines`.
309 This is essentially a robust wrapper around `inspect.getsourcelines`.
310
310
311 Returns None if no file can be found.
311 Returns None if no file can be found.
312
312
313 Parameters
313 Parameters
314 ----------
314 ----------
315 obj : any Python object
315 obj : any Python object
316
316
317 Returns
317 Returns
318 -------
318 -------
319 lineno : int
319 lineno : int
320 The line number where the object definition starts.
320 The line number where the object definition starts.
321 """
321 """
322 # get source if obj was decorated with @decorator
322 # get source if obj was decorated with @decorator
323 if safe_hasattr(obj, '__wrapped__'):
323 if safe_hasattr(obj, '__wrapped__'):
324 obj = obj.__wrapped__
324 obj = obj.__wrapped__
325
325
326 try:
326 try:
327 try:
327 try:
328 lineno = inspect.getsourcelines(obj)[1]
328 lineno = inspect.getsourcelines(obj)[1]
329 except TypeError:
329 except TypeError:
330 # For instances, try the class object like getsource() does
330 # For instances, try the class object like getsource() does
331 if hasattr(obj, '__class__'):
331 if hasattr(obj, '__class__'):
332 lineno = inspect.getsourcelines(obj.__class__)[1]
332 lineno = inspect.getsourcelines(obj.__class__)[1]
333 else:
333 else:
334 lineno = None
334 lineno = None
335 except:
335 except:
336 return None
336 return None
337
337
338 return lineno
338 return lineno
339
339
340
340
341 class Inspector:
341 class Inspector:
342 def __init__(self, color_table=InspectColors,
342 def __init__(self, color_table=InspectColors,
343 code_color_table=PyColorize.ANSICodeColors,
343 code_color_table=PyColorize.ANSICodeColors,
344 scheme='NoColor',
344 scheme='NoColor',
345 str_detail_level=0):
345 str_detail_level=0):
346 self.color_table = color_table
346 self.color_table = color_table
347 self.parser = PyColorize.Parser(code_color_table,out='str')
347 self.parser = PyColorize.Parser(code_color_table,out='str')
348 self.format = self.parser.format
348 self.format = self.parser.format
349 self.str_detail_level = str_detail_level
349 self.str_detail_level = str_detail_level
350 self.set_active_scheme(scheme)
350 self.set_active_scheme(scheme)
351
351
352 def _getdef(self,obj,oname=''):
352 def _getdef(self,obj,oname=''):
353 """Return the call signature for any callable object.
353 """Return the call signature for any callable object.
354
354
355 If any exception is generated, None is returned instead and the
355 If any exception is generated, None is returned instead and the
356 exception is suppressed."""
356 exception is suppressed."""
357 try:
357 try:
358 hdef = oname + inspect.formatargspec(*getargspec(obj))
358 hdef = oname + inspect.formatargspec(*getargspec(obj))
359 return cast_unicode(hdef)
359 return cast_unicode(hdef)
360 except:
360 except:
361 return None
361 return None
362
362
363 def __head(self,h):
363 def __head(self,h):
364 """Return a header string with proper colors."""
364 """Return a header string with proper colors."""
365 return '%s%s%s' % (self.color_table.active_colors.header,h,
365 return '%s%s%s' % (self.color_table.active_colors.header,h,
366 self.color_table.active_colors.normal)
366 self.color_table.active_colors.normal)
367
367
368 def set_active_scheme(self, scheme):
368 def set_active_scheme(self, scheme):
369 self.color_table.set_active_scheme(scheme)
369 self.color_table.set_active_scheme(scheme)
370 self.parser.color_table.set_active_scheme(scheme)
370 self.parser.color_table.set_active_scheme(scheme)
371
371
372 def noinfo(self, msg, oname):
372 def noinfo(self, msg, oname):
373 """Generic message when no information is found."""
373 """Generic message when no information is found."""
374 print('No %s found' % msg, end=' ')
374 print('No %s found' % msg, end=' ')
375 if oname:
375 if oname:
376 print('for %s' % oname)
376 print('for %s' % oname)
377 else:
377 else:
378 print()
378 print()
379
379
380 def pdef(self, obj, oname=''):
380 def pdef(self, obj, oname=''):
381 """Print the call signature for any callable object.
381 """Print the call signature for any callable object.
382
382
383 If the object is a class, print the constructor information."""
383 If the object is a class, print the constructor information."""
384
384
385 if not callable(obj):
385 if not callable(obj):
386 print('Object is not callable.')
386 print('Object is not callable.')
387 return
387 return
388
388
389 header = ''
389 header = ''
390
390
391 if inspect.isclass(obj):
391 if inspect.isclass(obj):
392 header = self.__head('Class constructor information:\n')
392 header = self.__head('Class constructor information:\n')
393 obj = obj.__init__
393 obj = obj.__init__
394 elif (not py3compat.PY3) and type(obj) is types.InstanceType:
394 elif (not py3compat.PY3) and type(obj) is types.InstanceType:
395 obj = obj.__call__
395 obj = obj.__call__
396
396
397 output = self._getdef(obj,oname)
397 output = self._getdef(obj,oname)
398 if output is None:
398 if output is None:
399 self.noinfo('definition header',oname)
399 self.noinfo('definition header',oname)
400 else:
400 else:
401 print(header,self.format(output), end=' ', file=io.stdout)
401 print(header,self.format(output), end=' ', file=io.stdout)
402
402
403 # In Python 3, all classes are new-style, so they all have __init__.
403 # In Python 3, all classes are new-style, so they all have __init__.
404 @skip_doctest_py3
404 @skip_doctest_py3
405 def pdoc(self,obj,oname='',formatter = None):
405 def pdoc(self,obj,oname='',formatter = None):
406 """Print the docstring for any object.
406 """Print the docstring for any object.
407
407
408 Optional:
408 Optional:
409 -formatter: a function to run the docstring through for specially
409 -formatter: a function to run the docstring through for specially
410 formatted docstrings.
410 formatted docstrings.
411
411
412 Examples
412 Examples
413 --------
413 --------
414
414
415 In [1]: class NoInit:
415 In [1]: class NoInit:
416 ...: pass
416 ...: pass
417
417
418 In [2]: class NoDoc:
418 In [2]: class NoDoc:
419 ...: def __init__(self):
419 ...: def __init__(self):
420 ...: pass
420 ...: pass
421
421
422 In [3]: %pdoc NoDoc
422 In [3]: %pdoc NoDoc
423 No documentation found for NoDoc
423 No documentation found for NoDoc
424
424
425 In [4]: %pdoc NoInit
425 In [4]: %pdoc NoInit
426 No documentation found for NoInit
426 No documentation found for NoInit
427
427
428 In [5]: obj = NoInit()
428 In [5]: obj = NoInit()
429
429
430 In [6]: %pdoc obj
430 In [6]: %pdoc obj
431 No documentation found for obj
431 No documentation found for obj
432
432
433 In [5]: obj2 = NoDoc()
433 In [5]: obj2 = NoDoc()
434
434
435 In [6]: %pdoc obj2
435 In [6]: %pdoc obj2
436 No documentation found for obj2
436 No documentation found for obj2
437 """
437 """
438
438
439 head = self.__head # For convenience
439 head = self.__head # For convenience
440 lines = []
440 lines = []
441 ds = getdoc(obj)
441 ds = getdoc(obj)
442 if formatter:
442 if formatter:
443 ds = formatter(ds)
443 ds = formatter(ds)
444 if ds:
444 if ds:
445 lines.append(head("Class Docstring:"))
445 lines.append(head("Class Docstring:"))
446 lines.append(indent(ds))
446 lines.append(indent(ds))
447 if inspect.isclass(obj) and hasattr(obj, '__init__'):
447 if inspect.isclass(obj) and hasattr(obj, '__init__'):
448 init_ds = getdoc(obj.__init__)
448 init_ds = getdoc(obj.__init__)
449 if init_ds is not None:
449 if init_ds is not None:
450 lines.append(head("Constructor Docstring:"))
450 lines.append(head("Constructor Docstring:"))
451 lines.append(indent(init_ds))
451 lines.append(indent(init_ds))
452 elif hasattr(obj,'__call__'):
452 elif hasattr(obj,'__call__'):
453 call_ds = getdoc(obj.__call__)
453 call_ds = getdoc(obj.__call__)
454 if call_ds:
454 if call_ds:
455 lines.append(head("Calling Docstring:"))
455 lines.append(head("Calling Docstring:"))
456 lines.append(indent(call_ds))
456 lines.append(indent(call_ds))
457
457
458 if not lines:
458 if not lines:
459 self.noinfo('documentation',oname)
459 self.noinfo('documentation',oname)
460 else:
460 else:
461 page.page('\n'.join(lines))
461 page.page('\n'.join(lines))
462
462
463 def psource(self,obj,oname=''):
463 def psource(self,obj,oname=''):
464 """Print the source code for an object."""
464 """Print the source code for an object."""
465
465
466 # Flush the source cache because inspect can return out-of-date source
466 # Flush the source cache because inspect can return out-of-date source
467 linecache.checkcache()
467 linecache.checkcache()
468 try:
468 try:
469 src = getsource(obj)
469 src = getsource(obj)
470 except:
470 except:
471 self.noinfo('source',oname)
471 self.noinfo('source',oname)
472 else:
472 else:
473 page.page(self.format(src))
473 page.page(self.format(src))
474
474
475 def pfile(self, obj, oname=''):
475 def pfile(self, obj, oname=''):
476 """Show the whole file where an object was defined."""
476 """Show the whole file where an object was defined."""
477
477
478 lineno = find_source_lines(obj)
478 lineno = find_source_lines(obj)
479 if lineno is None:
479 if lineno is None:
480 self.noinfo('file', oname)
480 self.noinfo('file', oname)
481 return
481 return
482
482
483 ofile = find_file(obj)
483 ofile = find_file(obj)
484 # run contents of file through pager starting at line where the object
484 # run contents of file through pager starting at line where the object
485 # is defined, as long as the file isn't binary and is actually on the
485 # is defined, as long as the file isn't binary and is actually on the
486 # filesystem.
486 # filesystem.
487 if ofile.endswith(('.so', '.dll', '.pyd')):
487 if ofile.endswith(('.so', '.dll', '.pyd')):
488 print('File %r is binary, not printing.' % ofile)
488 print('File %r is binary, not printing.' % ofile)
489 elif not os.path.isfile(ofile):
489 elif not os.path.isfile(ofile):
490 print('File %r does not exist, not printing.' % ofile)
490 print('File %r does not exist, not printing.' % ofile)
491 else:
491 else:
492 # Print only text files, not extension binaries. Note that
492 # Print only text files, not extension binaries. Note that
493 # getsourcelines returns lineno with 1-offset and page() uses
493 # getsourcelines returns lineno with 1-offset and page() uses
494 # 0-offset, so we must adjust.
494 # 0-offset, so we must adjust.
495 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
495 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
496
496
497 def _format_fields(self, fields, title_width=12):
497 def _format_fields(self, fields, title_width=12):
498 """Formats a list of fields for display.
498 """Formats a list of fields for display.
499
499
500 Parameters
500 Parameters
501 ----------
501 ----------
502 fields : list
502 fields : list
503 A list of 2-tuples: (field_title, field_content)
503 A list of 2-tuples: (field_title, field_content)
504 title_width : int
504 title_width : int
505 How many characters to pad titles to. Default 12.
505 How many characters to pad titles to. Default 12.
506 """
506 """
507 out = []
507 out = []
508 header = self.__head
508 header = self.__head
509 for title, content in fields:
509 for title, content in fields:
510 if len(content.splitlines()) > 1:
510 if len(content.splitlines()) > 1:
511 title = header(title + ":") + "\n"
511 title = header(title + ":") + "\n"
512 else:
512 else:
513 title = header((title+":").ljust(title_width))
513 title = header((title+":").ljust(title_width))
514 out.append(cast_unicode(title) + cast_unicode(content))
514 out.append(cast_unicode(title) + cast_unicode(content))
515 return "\n".join(out)
515 return "\n".join(out)
516
516
517 # The fields to be displayed by pinfo: (fancy_name, key_in_info_dict)
517 # The fields to be displayed by pinfo: (fancy_name, key_in_info_dict)
518 pinfo_fields1 = [("Type", "type_name"),
518 pinfo_fields1 = [("Type", "type_name"),
519 ]
519 ]
520
520
521 pinfo_fields2 = [("String Form", "string_form"),
521 pinfo_fields2 = [("String Form", "string_form"),
522 ]
522 ]
523
523
524 pinfo_fields3 = [("Length", "length"),
524 pinfo_fields3 = [("Length", "length"),
525 ("File", "file"),
525 ("File", "file"),
526 ("Definition", "definition"),
526 ("Definition", "definition"),
527 ]
527 ]
528
528
529 pinfo_fields_obj = [("Class Docstring", "class_docstring"),
529 pinfo_fields_obj = [("Class Docstring", "class_docstring"),
530 ("Constructor Docstring","init_docstring"),
530 ("Constructor Docstring","init_docstring"),
531 ("Call def", "call_def"),
531 ("Call def", "call_def"),
532 ("Call docstring", "call_docstring")]
532 ("Call docstring", "call_docstring")]
533
533
534 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
534 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
535 """Show detailed information about an object.
535 """Show detailed information about an object.
536
536
537 Optional arguments:
537 Optional arguments:
538
538
539 - oname: name of the variable pointing to the object.
539 - oname: name of the variable pointing to the object.
540
540
541 - formatter: special formatter for docstrings (see pdoc)
541 - formatter: special formatter for docstrings (see pdoc)
542
542
543 - info: a structure with some information fields which may have been
543 - info: a structure with some information fields which may have been
544 precomputed already.
544 precomputed already.
545
545
546 - detail_level: if set to 1, more information is given.
546 - detail_level: if set to 1, more information is given.
547 """
547 """
548 info = self.info(obj, oname=oname, formatter=formatter,
548 info = self.info(obj, oname=oname, formatter=formatter,
549 info=info, detail_level=detail_level)
549 info=info, detail_level=detail_level)
550 displayfields = []
550 displayfields = []
551 def add_fields(fields):
551 def add_fields(fields):
552 for title, key in fields:
552 for title, key in fields:
553 field = info[key]
553 field = info[key]
554 if field is not None:
554 if field is not None:
555 displayfields.append((title, field.rstrip()))
555 displayfields.append((title, field.rstrip()))
556
556
557 add_fields(self.pinfo_fields1)
557 add_fields(self.pinfo_fields1)
558
558
559 # Base class for old-style instances
559 # Base class for old-style instances
560 if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
560 if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
561 displayfields.append(("Base Class", info['base_class'].rstrip()))
561 displayfields.append(("Base Class", info['base_class'].rstrip()))
562
562
563 add_fields(self.pinfo_fields2)
563 add_fields(self.pinfo_fields2)
564
564
565 # Namespace
565 # Namespace
566 if info['namespace'] != 'Interactive':
566 if info['namespace'] != 'Interactive':
567 displayfields.append(("Namespace", info['namespace'].rstrip()))
567 displayfields.append(("Namespace", info['namespace'].rstrip()))
568
568
569 add_fields(self.pinfo_fields3)
569 add_fields(self.pinfo_fields3)
570
570
571 # Source or docstring, depending on detail level and whether
571 # Source or docstring, depending on detail level and whether
572 # source found.
572 # source found.
573 if detail_level > 0 and info['source'] is not None:
573 if detail_level > 0 and info['source'] is not None:
574 displayfields.append(("Source",
574 displayfields.append(("Source",
575 self.format(cast_unicode(info['source']))))
575 self.format(cast_unicode(info['source']))))
576 elif info['docstring'] is not None:
576 elif info['docstring'] is not None:
577 displayfields.append(("Docstring", info["docstring"]))
577 displayfields.append(("Docstring", info["docstring"]))
578
578
579 # Constructor info for classes
579 # Constructor info for classes
580 if info['isclass']:
580 if info['isclass']:
581 if info['init_definition'] or info['init_docstring']:
581 if info['init_definition'] or info['init_docstring']:
582 displayfields.append(("Constructor information", ""))
582 displayfields.append(("Constructor information", ""))
583 if info['init_definition'] is not None:
583 if info['init_definition'] is not None:
584 displayfields.append((" Definition",
584 displayfields.append((" Definition",
585 info['init_definition'].rstrip()))
585 info['init_definition'].rstrip()))
586 if info['init_docstring'] is not None:
586 if info['init_docstring'] is not None:
587 displayfields.append((" Docstring",
587 displayfields.append((" Docstring",
588 indent(info['init_docstring'])))
588 indent(info['init_docstring'])))
589
589
590 # Info for objects:
590 # Info for objects:
591 else:
591 else:
592 add_fields(self.pinfo_fields_obj)
592 add_fields(self.pinfo_fields_obj)
593
593
594 # Finally send to printer/pager:
594 # Finally send to printer/pager:
595 if displayfields:
595 if displayfields:
596 page.page(self._format_fields(displayfields))
596 page.page(self._format_fields(displayfields))
597
597
598 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
598 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
599 """Compute a dict with detailed information about an object.
599 """Compute a dict with detailed information about an object.
600
600
601 Optional arguments:
601 Optional arguments:
602
602
603 - oname: name of the variable pointing to the object.
603 - oname: name of the variable pointing to the object.
604
604
605 - formatter: special formatter for docstrings (see pdoc)
605 - formatter: special formatter for docstrings (see pdoc)
606
606
607 - info: a structure with some information fields which may have been
607 - info: a structure with some information fields which may have been
608 precomputed already.
608 precomputed already.
609
609
610 - detail_level: if set to 1, more information is given.
610 - detail_level: if set to 1, more information is given.
611 """
611 """
612
612
613 obj_type = type(obj)
613 obj_type = type(obj)
614
614
615 if info is None:
615 if info is None:
616 ismagic = 0
616 ismagic = 0
617 isalias = 0
617 isalias = 0
618 ospace = ''
618 ospace = ''
619 else:
619 else:
620 ismagic = info.ismagic
620 ismagic = info.ismagic
621 isalias = info.isalias
621 isalias = info.isalias
622 ospace = info.namespace
622 ospace = info.namespace
623
623
624 # Get docstring, special-casing aliases:
624 # Get docstring, special-casing aliases:
625 if isalias:
625 if isalias:
626 if not callable(obj):
626 if not callable(obj):
627 try:
627 try:
628 ds = "Alias to the system command:\n %s" % obj[1]
628 ds = "Alias to the system command:\n %s" % obj[1]
629 except:
629 except:
630 ds = "Alias: " + str(obj)
630 ds = "Alias: " + str(obj)
631 else:
631 else:
632 ds = "Alias to " + str(obj)
632 ds = "Alias to " + str(obj)
633 if obj.__doc__:
633 if obj.__doc__:
634 ds += "\nDocstring:\n" + obj.__doc__
634 ds += "\nDocstring:\n" + obj.__doc__
635 else:
635 else:
636 ds = getdoc(obj)
636 ds = getdoc(obj)
637 if ds is None:
637 if ds is None:
638 ds = '<no docstring>'
638 ds = '<no docstring>'
639 if formatter is not None:
639 if formatter is not None:
640 ds = formatter(ds)
640 ds = formatter(ds)
641
641
642 # store output in a dict, we initialize it here and fill it as we go
642 # store output in a dict, we initialize it here and fill it as we go
643 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
643 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
644
644
645 string_max = 200 # max size of strings to show (snipped if longer)
645 string_max = 200 # max size of strings to show (snipped if longer)
646 shalf = int((string_max -5)/2)
646 shalf = int((string_max -5)/2)
647
647
648 if ismagic:
648 if ismagic:
649 obj_type_name = 'Magic function'
649 obj_type_name = 'Magic function'
650 elif isalias:
650 elif isalias:
651 obj_type_name = 'System alias'
651 obj_type_name = 'System alias'
652 else:
652 else:
653 obj_type_name = obj_type.__name__
653 obj_type_name = obj_type.__name__
654 out['type_name'] = obj_type_name
654 out['type_name'] = obj_type_name
655
655
656 try:
656 try:
657 bclass = obj.__class__
657 bclass = obj.__class__
658 out['base_class'] = str(bclass)
658 out['base_class'] = str(bclass)
659 except: pass
659 except: pass
660
660
661 # String form, but snip if too long in ? form (full in ??)
661 # String form, but snip if too long in ? form (full in ??)
662 if detail_level >= self.str_detail_level:
662 if detail_level >= self.str_detail_level:
663 try:
663 try:
664 ostr = str(obj)
664 ostr = str(obj)
665 str_head = 'string_form'
665 str_head = 'string_form'
666 if not detail_level and len(ostr)>string_max:
666 if not detail_level and len(ostr)>string_max:
667 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
667 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
668 ostr = ("\n" + " " * len(str_head.expandtabs())).\
668 ostr = ("\n" + " " * len(str_head.expandtabs())).\
669 join(q.strip() for q in ostr.split("\n"))
669 join(q.strip() for q in ostr.split("\n"))
670 out[str_head] = ostr
670 out[str_head] = ostr
671 except:
671 except:
672 pass
672 pass
673
673
674 if ospace:
674 if ospace:
675 out['namespace'] = ospace
675 out['namespace'] = ospace
676
676
677 # Length (for strings and lists)
677 # Length (for strings and lists)
678 try:
678 try:
679 out['length'] = str(len(obj))
679 out['length'] = str(len(obj))
680 except: pass
680 except: pass
681
681
682 # Filename where object was defined
682 # Filename where object was defined
683 binary_file = False
683 binary_file = False
684 fname = find_file(obj)
684 fname = find_file(obj)
685 if fname is None:
685 if fname is None:
686 # if anything goes wrong, we don't want to show source, so it's as
686 # if anything goes wrong, we don't want to show source, so it's as
687 # if the file was binary
687 # if the file was binary
688 binary_file = True
688 binary_file = True
689 else:
689 else:
690 if fname.endswith(('.so', '.dll', '.pyd')):
690 if fname.endswith(('.so', '.dll', '.pyd')):
691 binary_file = True
691 binary_file = True
692 elif fname.endswith('<string>'):
692 elif fname.endswith('<string>'):
693 fname = 'Dynamically generated function. No source code available.'
693 fname = 'Dynamically generated function. No source code available.'
694 out['file'] = fname
694 out['file'] = fname
695
695
696 # reconstruct the function definition and print it:
696 # reconstruct the function definition and print it:
697 defln = self._getdef(obj, oname)
697 defln = self._getdef(obj, oname)
698 if defln:
698 if defln:
699 out['definition'] = self.format(defln)
699 out['definition'] = self.format(defln)
700
700
701 # Docstrings only in detail 0 mode, since source contains them (we
701 # Docstrings only in detail 0 mode, since source contains them (we
702 # avoid repetitions). If source fails, we add them back, see below.
702 # avoid repetitions). If source fails, we add them back, see below.
703 if ds and detail_level == 0:
703 if ds and detail_level == 0:
704 out['docstring'] = ds
704 out['docstring'] = ds
705
705
706 # Original source code for any callable
706 # Original source code for any callable
707 if detail_level:
707 if detail_level:
708 # Flush the source cache because inspect can return out-of-date
708 # Flush the source cache because inspect can return out-of-date
709 # source
709 # source
710 linecache.checkcache()
710 linecache.checkcache()
711 source = None
711 source = None
712 try:
712 try:
713 try:
713 try:
714 source = getsource(obj, binary_file)
714 source = getsource(obj, binary_file)
715 except TypeError:
715 except TypeError:
716 if hasattr(obj, '__class__'):
716 if hasattr(obj, '__class__'):
717 source = getsource(obj.__class__, binary_file)
717 source = getsource(obj.__class__, binary_file)
718 if source is not None:
718 if source is not None:
719 out['source'] = source.rstrip()
719 out['source'] = source.rstrip()
720 except Exception:
720 except Exception:
721 pass
721 pass
722
722
723 if ds and source is None:
723 if ds and source is None:
724 out['docstring'] = ds
724 out['docstring'] = ds
725
725
726
726
727 # Constructor docstring for classes
727 # Constructor docstring for classes
728 if inspect.isclass(obj):
728 if inspect.isclass(obj):
729 out['isclass'] = True
729 out['isclass'] = True
730 # reconstruct the function definition and print it:
730 # reconstruct the function definition and print it:
731 try:
731 try:
732 obj_init = obj.__init__
732 obj_init = obj.__init__
733 except AttributeError:
733 except AttributeError:
734 init_def = init_ds = None
734 init_def = init_ds = None
735 else:
735 else:
736 init_def = self._getdef(obj_init,oname)
736 init_def = self._getdef(obj_init,oname)
737 init_ds = getdoc(obj_init)
737 init_ds = getdoc(obj_init)
738 # Skip Python's auto-generated docstrings
738 # Skip Python's auto-generated docstrings
739 if init_ds == _object_init_docstring:
739 if init_ds == _object_init_docstring:
740 init_ds = None
740 init_ds = None
741
741
742 if init_def or init_ds:
742 if init_def or init_ds:
743 if init_def:
743 if init_def:
744 out['init_definition'] = self.format(init_def)
744 out['init_definition'] = self.format(init_def)
745 if init_ds:
745 if init_ds:
746 out['init_docstring'] = init_ds
746 out['init_docstring'] = init_ds
747
747
748 # and class docstring for instances:
748 # and class docstring for instances:
749 else:
749 else:
750 # First, check whether the instance docstring is identical to the
750 # First, check whether the instance docstring is identical to the
751 # class one, and print it separately if they don't coincide. In
751 # class one, and print it separately if they don't coincide. In
752 # most cases they will, but it's nice to print all the info for
752 # most cases they will, but it's nice to print all the info for
753 # objects which use instance-customized docstrings.
753 # objects which use instance-customized docstrings.
754 if ds:
754 if ds:
755 try:
755 try:
756 cls = getattr(obj,'__class__')
756 cls = getattr(obj,'__class__')
757 except:
757 except:
758 class_ds = None
758 class_ds = None
759 else:
759 else:
760 class_ds = getdoc(cls)
760 class_ds = getdoc(cls)
761 # Skip Python's auto-generated docstrings
761 # Skip Python's auto-generated docstrings
762 if class_ds in _builtin_type_docstrings:
762 if class_ds in _builtin_type_docstrings:
763 class_ds = None
763 class_ds = None
764 if class_ds and ds != class_ds:
764 if class_ds and ds != class_ds:
765 out['class_docstring'] = class_ds
765 out['class_docstring'] = class_ds
766
766
767 # Next, try to show constructor docstrings
767 # Next, try to show constructor docstrings
768 try:
768 try:
769 init_ds = getdoc(obj.__init__)
769 init_ds = getdoc(obj.__init__)
770 # Skip Python's auto-generated docstrings
770 # Skip Python's auto-generated docstrings
771 if init_ds == _object_init_docstring:
771 if init_ds == _object_init_docstring:
772 init_ds = None
772 init_ds = None
773 except AttributeError:
773 except AttributeError:
774 init_ds = None
774 init_ds = None
775 if init_ds:
775 if init_ds:
776 out['init_docstring'] = init_ds
776 out['init_docstring'] = init_ds
777
777
778 # Call form docstring for callable instances
778 # Call form docstring for callable instances
779 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
779 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
780 call_def = self._getdef(obj.__call__, oname)
780 call_def = self._getdef(obj.__call__, oname)
781 if call_def is not None:
781 if call_def is not None:
782 out['call_def'] = self.format(call_def)
782 out['call_def'] = self.format(call_def)
783 call_ds = getdoc(obj.__call__)
783 call_ds = getdoc(obj.__call__)
784 # Skip Python's auto-generated docstrings
784 # Skip Python's auto-generated docstrings
785 if call_ds == _func_call_docstring:
785 if call_ds == _func_call_docstring:
786 call_ds = None
786 call_ds = None
787 if call_ds:
787 if call_ds:
788 out['call_docstring'] = call_ds
788 out['call_docstring'] = call_ds
789
789
790 # Compute the object's argspec as a callable. The key is to decide
790 # Compute the object's argspec as a callable. The key is to decide
791 # whether to pull it from the object itself, from its __init__ or
791 # whether to pull it from the object itself, from its __init__ or
792 # from its __call__ method.
792 # from its __call__ method.
793
793
794 if inspect.isclass(obj):
794 if inspect.isclass(obj):
795 # Old-style classes need not have an __init__
795 # Old-style classes need not have an __init__
796 callable_obj = getattr(obj, "__init__", None)
796 callable_obj = getattr(obj, "__init__", None)
797 elif callable(obj):
797 elif callable(obj):
798 callable_obj = obj
798 callable_obj = obj
799 else:
799 else:
800 callable_obj = None
800 callable_obj = None
801
801
802 if callable_obj:
802 if callable_obj:
803 try:
803 try:
804 argspec = getargspec(callable_obj)
804 argspec = getargspec(callable_obj)
805 except (TypeError, AttributeError):
805 except (TypeError, AttributeError):
806 # For extensions/builtins we can't retrieve the argspec
806 # For extensions/builtins we can't retrieve the argspec
807 pass
807 pass
808 else:
808 else:
809 # named tuples' _asdict() method returns an OrderedDict, but we
809 # named tuples' _asdict() method returns an OrderedDict, but we
810 # we want a normal
810 # we want a normal
811 out['argspec'] = argspec_dict = dict(argspec._asdict())
811 out['argspec'] = argspec_dict = dict(argspec._asdict())
812 # We called this varkw before argspec became a named tuple.
812 # We called this varkw before argspec became a named tuple.
813 # With getfullargspec it's also called varkw.
813 # With getfullargspec it's also called varkw.
814 if 'varkw' not in argspec_dict:
814 if 'varkw' not in argspec_dict:
815 argspec_dict['varkw'] = argspec_dict.pop('keywords')
815 argspec_dict['varkw'] = argspec_dict.pop('keywords')
816
816
817 return object_info(**out)
817 return object_info(**out)
818
818
819
819
820 def psearch(self,pattern,ns_table,ns_search=[],
820 def psearch(self,pattern,ns_table,ns_search=[],
821 ignore_case=False,show_all=False):
821 ignore_case=False,show_all=False):
822 """Search namespaces with wildcards for objects.
822 """Search namespaces with wildcards for objects.
823
823
824 Arguments:
824 Arguments:
825
825
826 - pattern: string containing shell-like wildcards to use in namespace
826 - pattern: string containing shell-like wildcards to use in namespace
827 searches and optionally a type specification to narrow the search to
827 searches and optionally a type specification to narrow the search to
828 objects of that type.
828 objects of that type.
829
829
830 - ns_table: dict of name->namespaces for search.
830 - ns_table: dict of name->namespaces for search.
831
831
832 Optional arguments:
832 Optional arguments:
833
833
834 - ns_search: list of namespace names to include in search.
834 - ns_search: list of namespace names to include in search.
835
835
836 - ignore_case(False): make the search case-insensitive.
836 - ignore_case(False): make the search case-insensitive.
837
837
838 - show_all(False): show all names, including those starting with
838 - show_all(False): show all names, including those starting with
839 underscores.
839 underscores.
840 """
840 """
841 #print 'ps pattern:<%r>' % pattern # dbg
841 #print 'ps pattern:<%r>' % pattern # dbg
842
842
843 # defaults
843 # defaults
844 type_pattern = 'all'
844 type_pattern = 'all'
845 filter = ''
845 filter = ''
846
846
847 cmds = pattern.split()
847 cmds = pattern.split()
848 len_cmds = len(cmds)
848 len_cmds = len(cmds)
849 if len_cmds == 1:
849 if len_cmds == 1:
850 # Only filter pattern given
850 # Only filter pattern given
851 filter = cmds[0]
851 filter = cmds[0]
852 elif len_cmds == 2:
852 elif len_cmds == 2:
853 # Both filter and type specified
853 # Both filter and type specified
854 filter,type_pattern = cmds
854 filter,type_pattern = cmds
855 else:
855 else:
856 raise ValueError('invalid argument string for psearch: <%s>' %
856 raise ValueError('invalid argument string for psearch: <%s>' %
857 pattern)
857 pattern)
858
858
859 # filter search namespaces
859 # filter search namespaces
860 for name in ns_search:
860 for name in ns_search:
861 if name not in ns_table:
861 if name not in ns_table:
862 raise ValueError('invalid namespace <%s>. Valid names: %s' %
862 raise ValueError('invalid namespace <%s>. Valid names: %s' %
863 (name,ns_table.keys()))
863 (name,ns_table.keys()))
864
864
865 #print 'type_pattern:',type_pattern # dbg
865 #print 'type_pattern:',type_pattern # dbg
866 search_result, namespaces_seen = set(), set()
866 search_result, namespaces_seen = set(), set()
867 for ns_name in ns_search:
867 for ns_name in ns_search:
868 ns = ns_table[ns_name]
868 ns = ns_table[ns_name]
869 # Normally, locals and globals are the same, so we just check one.
869 # Normally, locals and globals are the same, so we just check one.
870 if id(ns) in namespaces_seen:
870 if id(ns) in namespaces_seen:
871 continue
871 continue
872 namespaces_seen.add(id(ns))
872 namespaces_seen.add(id(ns))
873 tmp_res = list_namespace(ns, type_pattern, filter,
873 tmp_res = list_namespace(ns, type_pattern, filter,
874 ignore_case=ignore_case, show_all=show_all)
874 ignore_case=ignore_case, show_all=show_all)
875 search_result.update(tmp_res)
875 search_result.update(tmp_res)
876
876
877 page.page('\n'.join(sorted(search_result)))
877 page.page('\n'.join(sorted(search_result)))
General Comments 0
You need to be logged in to leave comments. Login now