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