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