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