##// END OF EJS Templates
Apply suggestions from code review...
Matthias Bussonnier -
Show More
@@ -1,1055 +1,1055 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 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12
13 13 __all__ = ['Inspector','InspectColors']
14 14
15 15 # stdlib modules
16 16 import ast
17 17 import inspect
18 18 from inspect import signature
19 19 import linecache
20 20 import warnings
21 21 import os
22 22 from textwrap import dedent
23 23 import types
24 24 import io as stdlib_io
25 25
26 26 from typing import Union
27 27
28 28 # IPython's own
29 29 from IPython.core import page
30 30 from IPython.lib.pretty import pretty
31 31 from IPython.testing.skipdoctest import skip_doctest
32 32 from IPython.utils import PyColorize
33 33 from IPython.utils import openpy
34 34 from IPython.utils import py3compat
35 35 from IPython.utils.dir2 import safe_hasattr
36 36 from IPython.utils.path import compress_user
37 37 from IPython.utils.text import indent
38 38 from IPython.utils.wildcard import list_namespace
39 39 from IPython.utils.wildcard import typestr2type
40 40 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
41 41 from IPython.utils.py3compat import cast_unicode
42 42 from IPython.utils.colorable import Colorable
43 43 from IPython.utils.decorators import undoc
44 44
45 45 from pygments import highlight
46 46 from pygments.lexers import PythonLexer
47 47 from pygments.formatters import HtmlFormatter
48 48
49 49 def pylight(code):
50 50 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
51 51
52 52 # builtin docstrings to ignore
53 53 _func_call_docstring = types.FunctionType.__call__.__doc__
54 54 _object_init_docstring = object.__init__.__doc__
55 55 _builtin_type_docstrings = {
56 56 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
57 57 types.FunctionType, property)
58 58 }
59 59
60 60 _builtin_func_type = type(all)
61 61 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
62 62 #****************************************************************************
63 63 # Builtin color schemes
64 64
65 65 Colors = TermColors # just a shorthand
66 66
67 67 InspectColors = PyColorize.ANSICodeColors
68 68
69 69 #****************************************************************************
70 70 # Auxiliary functions and objects
71 71
72 72 # See the messaging spec for the definition of all these fields. This list
73 73 # effectively defines the order of display
74 74 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
75 75 'length', 'file', 'definition', 'docstring', 'source',
76 76 'init_definition', 'class_docstring', 'init_docstring',
77 77 'call_def', 'call_docstring',
78 78 # These won't be printed but will be used to determine how to
79 79 # format the object
80 80 'ismagic', 'isalias', 'isclass', 'found', 'name'
81 81 ]
82 82
83 83
84 84 def object_info(**kw):
85 85 """Make an object info dict with all fields present."""
86 86 infodict = {k:None for k in info_fields}
87 87 infodict.update(kw)
88 88 return infodict
89 89
90 90
91 91 def get_encoding(obj):
92 92 """Get encoding for python source file defining obj
93 93
94 94 Returns None if obj is not defined in a sourcefile.
95 95 """
96 96 ofile = find_file(obj)
97 97 # run contents of file through pager starting at line where the object
98 98 # is defined, as long as the file isn't binary and is actually on the
99 99 # filesystem.
100 100 if ofile is None:
101 101 return None
102 102 elif ofile.endswith(('.so', '.dll', '.pyd')):
103 103 return None
104 104 elif not os.path.isfile(ofile):
105 105 return None
106 106 else:
107 107 # Print only text files, not extension binaries. Note that
108 108 # getsourcelines returns lineno with 1-offset and page() uses
109 109 # 0-offset, so we must adjust.
110 110 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
111 111 encoding, lines = openpy.detect_encoding(buffer.readline)
112 112 return encoding
113 113
114 114 def getdoc(obj) -> Union[str,None]:
115 115 """Stable wrapper around inspect.getdoc.
116 116
117 117 This can't crash because of attribute problems.
118 118
119 119 It also attempts to call a getdoc() method on the given object. This
120 120 allows objects which provide their docstrings via non-standard mechanisms
121 121 (like Pyro proxies) to still be inspected by ipython's ? system.
122 122 """
123 123 # Allow objects to offer customized documentation via a getdoc method:
124 124 try:
125 125 ds = obj.getdoc()
126 126 except Exception:
127 127 pass
128 128 else:
129 129 if isinstance(ds, str):
130 130 return inspect.cleandoc(ds)
131 131 docstr = inspect.getdoc(obj)
132 132 return docstr
133 133
134 134
135 135 def getsource(obj, oname='') -> Union[str,None]:
136 136 """Wrapper around inspect.getsource.
137 137
138 138 This can be modified by other projects to provide customized source
139 139 extraction.
140 140
141 141 Parameters
142 142 ----------
143 143 obj : object
144 144 an object whose source code we will attempt to extract
145 145 oname : str
146 146 (optional) a name under which the object is known
147 147
148 148 Returns
149 149 -------
150 150 src : unicode or None
151 151
152 152 """
153 153
154 154 if isinstance(obj, property):
155 155 sources = []
156 156 for attrname in ['fget', 'fset', 'fdel']:
157 157 fn = getattr(obj, attrname)
158 158 if fn is not None:
159 159 encoding = get_encoding(fn)
160 160 oname_prefix = ('%s.' % oname) if oname else ''
161 161 sources.append(''.join(('# ', oname_prefix, attrname)))
162 162 if inspect.isfunction(fn):
163 163 sources.append(dedent(getsource(fn)))
164 164 else:
165 165 # Default str/repr only prints function name,
166 166 # pretty.pretty prints module name too.
167 167 sources.append(
168 168 '%s%s = %s\n' % (oname_prefix, attrname, pretty(fn))
169 169 )
170 170 if sources:
171 171 return '\n'.join(sources)
172 172 else:
173 173 return None
174 174
175 175 else:
176 176 # Get source for non-property objects.
177 177
178 178 obj = _get_wrapped(obj)
179 179
180 180 try:
181 181 src = inspect.getsource(obj)
182 182 except TypeError:
183 183 # The object itself provided no meaningful source, try looking for
184 184 # its class definition instead.
185 185 try:
186 186 src = inspect.getsource(obj.__class__)
187 187 except (OSError, TypeError):
188 188 return None
189 189 except OSError:
190 190 return None
191 191
192 192 return src
193 193
194 194
195 195 def is_simple_callable(obj):
196 196 """True if obj is a function ()"""
197 197 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
198 198 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
199 199
200 200 @undoc
201 201 def getargspec(obj):
202 202 """Wrapper around :func:`inspect.getfullargspec`
203 203
204 204 In addition to functions and methods, this can also handle objects with a
205 205 ``__call__`` attribute.
206 206
207 207 DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
208 208 """
209 209
210 210 warnings.warn('`getargspec` function is deprecated as of IPython 7.10'
211 211 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
212 212
213 213 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
214 214 obj = obj.__call__
215 215
216 216 return inspect.getfullargspec(obj)
217 217
218 218 @undoc
219 219 def format_argspec(argspec):
220 220 """Format argspect, convenience wrapper around inspect's.
221 221
222 222 This takes a dict instead of ordered arguments and calls
223 223 inspect.format_argspec with the arguments in the necessary order.
224 224
225 225 DEPRECATED (since 7.10): Do not use; will be removed in future versions.
226 226 """
227 227
228 228 warnings.warn('`format_argspec` function is deprecated as of IPython 7.10'
229 229 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
230 230
231 231
232 232 return inspect.formatargspec(argspec['args'], argspec['varargs'],
233 233 argspec['varkw'], argspec['defaults'])
234 234
235 235 @undoc
236 236 def call_tip(oinfo, format_call=True):
237 237 """DEPRECATED since 6.0. Extract call tip data from an oinfo dict."""
238 238 warnings.warn(
239 239 "`call_tip` function is deprecated as of IPython 6.0"
240 240 "and will be removed in future versions.",
241 241 DeprecationWarning,
242 242 stacklevel=2,
243 243 )
244 244 # Get call definition
245 245 argspec = oinfo.get('argspec')
246 246 if argspec is None:
247 247 call_line = None
248 248 else:
249 249 # Callable objects will have 'self' as their first argument, prune
250 250 # it out if it's there for clarity (since users do *not* pass an
251 251 # extra first argument explicitly).
252 252 try:
253 253 has_self = argspec['args'][0] == 'self'
254 254 except (KeyError, IndexError):
255 255 pass
256 256 else:
257 257 if has_self:
258 258 argspec['args'] = argspec['args'][1:]
259 259
260 260 call_line = oinfo['name']+format_argspec(argspec)
261 261
262 262 # Now get docstring.
263 263 # The priority is: call docstring, constructor docstring, main one.
264 264 doc = oinfo.get('call_docstring')
265 265 if doc is None:
266 266 doc = oinfo.get('init_docstring')
267 267 if doc is None:
268 268 doc = oinfo.get('docstring','')
269 269
270 270 return call_line, doc
271 271
272 272
273 273 def _get_wrapped(obj):
274 274 """Get the original object if wrapped in one or more @decorators
275 275
276 276 Some objects automatically construct similar objects on any unrecognised
277 277 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
278 278 this will arbitrarily cut off after 100 levels of obj.__wrapped__
279 279 attribute access. --TK, Jan 2016
280 280 """
281 281 orig_obj = obj
282 282 i = 0
283 283 while safe_hasattr(obj, '__wrapped__'):
284 284 obj = obj.__wrapped__
285 285 i += 1
286 286 if i > 100:
287 287 # __wrapped__ is probably a lie, so return the thing we started with
288 288 return orig_obj
289 289 return obj
290 290
291 291 def find_file(obj) -> str:
292 292 """Find the absolute path to the file where an object was defined.
293 293
294 294 This is essentially a robust wrapper around `inspect.getabsfile`.
295 295
296 296 Returns None if no file can be found.
297 297
298 298 Parameters
299 299 ----------
300 300 obj : any Python object
301 301
302 302 Returns
303 303 -------
304 304 fname : str
305 305 The absolute path to the file where the object was defined.
306 306 """
307 307 obj = _get_wrapped(obj)
308 308
309 309 fname = None
310 310 try:
311 311 fname = inspect.getabsfile(obj)
312 312 except TypeError:
313 313 # For an instance, the file that matters is where its class was
314 314 # declared.
315 315 try:
316 316 fname = inspect.getabsfile(obj.__class__)
317 317 except (OSError, TypeError):
318 318 # Can happen for builtins
319 319 pass
320 320 except OSError:
321 321 pass
322 322
323 323 return cast_unicode(fname)
324 324
325 325
326 326 def find_source_lines(obj):
327 327 """Find the line number in a file where an object was defined.
328 328
329 329 This is essentially a robust wrapper around `inspect.getsourcelines`.
330 330
331 331 Returns None if no file can be found.
332 332
333 333 Parameters
334 334 ----------
335 335 obj : any Python object
336 336
337 337 Returns
338 338 -------
339 339 lineno : int
340 340 The line number where the object definition starts.
341 341 """
342 342 obj = _get_wrapped(obj)
343 343
344 344 try:
345 345 lineno = inspect.getsourcelines(obj)[1]
346 346 except TypeError:
347 347 # For instances, try the class object like getsource() does
348 348 try:
349 349 lineno = inspect.getsourcelines(obj.__class__)[1]
350 350 except (OSError, TypeError):
351 351 return None
352 352 except OSError:
353 353 return None
354 354
355 355 return lineno
356 356
357 357 class Inspector(Colorable):
358 358
359 359 def __init__(self, color_table=InspectColors,
360 360 code_color_table=PyColorize.ANSICodeColors,
361 361 scheme=None,
362 362 str_detail_level=0,
363 363 parent=None, config=None):
364 364 super(Inspector, self).__init__(parent=parent, config=config)
365 365 self.color_table = color_table
366 366 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
367 367 self.format = self.parser.format
368 368 self.str_detail_level = str_detail_level
369 369 self.set_active_scheme(scheme)
370 370
371 371 def _getdef(self,obj,oname='') -> Union[str,None]:
372 372 """Return the call signature for any callable object.
373 373
374 374 If any exception is generated, None is returned instead and the
375 375 exception is suppressed."""
376 376 try:
377 377 return _render_signature(signature(obj), oname)
378 378 except:
379 379 return None
380 380
381 381 def __head(self,h) -> str:
382 382 """Return a header string with proper colors."""
383 383 return '%s%s%s' % (self.color_table.active_colors.header,h,
384 384 self.color_table.active_colors.normal)
385 385
386 386 def set_active_scheme(self, scheme):
387 387 if scheme is not None:
388 388 self.color_table.set_active_scheme(scheme)
389 389 self.parser.color_table.set_active_scheme(scheme)
390 390
391 391 def noinfo(self, msg, oname):
392 392 """Generic message when no information is found."""
393 393 print('No %s found' % msg, end=' ')
394 394 if oname:
395 395 print('for %s' % oname)
396 396 else:
397 397 print()
398 398
399 399 def pdef(self, obj, oname=''):
400 400 """Print the call signature for any callable object.
401 401
402 402 If the object is a class, print the constructor information."""
403 403
404 404 if not callable(obj):
405 405 print('Object is not callable.')
406 406 return
407 407
408 408 header = ''
409 409
410 410 if inspect.isclass(obj):
411 411 header = self.__head('Class constructor information:\n')
412 412
413 413
414 414 output = self._getdef(obj,oname)
415 415 if output is None:
416 416 self.noinfo('definition header',oname)
417 417 else:
418 418 print(header,self.format(output), end=' ')
419 419
420 420 # In Python 3, all classes are new-style, so they all have __init__.
421 421 @skip_doctest
422 422 def pdoc(self, obj, oname='', formatter=None):
423 423 """Print the docstring for any object.
424 424
425 425 Optional:
426 426 -formatter: a function to run the docstring through for specially
427 427 formatted docstrings.
428 428
429 429 Examples
430 430 --------
431 431 In [1]: class NoInit:
432 432 ...: pass
433 433
434 434 In [2]: class NoDoc:
435 435 ...: def __init__(self):
436 436 ...: pass
437 437
438 438 In [3]: %pdoc NoDoc
439 439 No documentation found for NoDoc
440 440
441 441 In [4]: %pdoc NoInit
442 442 No documentation found for NoInit
443 443
444 444 In [5]: obj = NoInit()
445 445
446 446 In [6]: %pdoc obj
447 447 No documentation found for obj
448 448
449 449 In [5]: obj2 = NoDoc()
450 450
451 451 In [6]: %pdoc obj2
452 452 No documentation found for obj2
453 453 """
454 454
455 455 head = self.__head # For convenience
456 456 lines = []
457 457 ds = getdoc(obj)
458 458 if formatter:
459 459 ds = formatter(ds).get('plain/text', ds)
460 460 if ds:
461 461 lines.append(head("Class docstring:"))
462 462 lines.append(indent(ds))
463 463 if inspect.isclass(obj) and hasattr(obj, '__init__'):
464 464 init_ds = getdoc(obj.__init__)
465 465 if init_ds is not None:
466 466 lines.append(head("Init docstring:"))
467 467 lines.append(indent(init_ds))
468 468 elif hasattr(obj,'__call__'):
469 469 call_ds = getdoc(obj.__call__)
470 470 if call_ds:
471 471 lines.append(head("Call docstring:"))
472 472 lines.append(indent(call_ds))
473 473
474 474 if not lines:
475 475 self.noinfo('documentation',oname)
476 476 else:
477 477 page.page('\n'.join(lines))
478 478
479 479 def psource(self, obj, oname=''):
480 480 """Print the source code for an object."""
481 481
482 482 # Flush the source cache because inspect can return out-of-date source
483 483 linecache.checkcache()
484 484 try:
485 485 src = getsource(obj, oname=oname)
486 486 except Exception:
487 487 src = None
488 488
489 489 if src is None:
490 490 self.noinfo('source', oname)
491 491 else:
492 492 page.page(self.format(src))
493 493
494 494 def pfile(self, obj, oname=''):
495 495 """Show the whole file where an object was defined."""
496 496
497 497 lineno = find_source_lines(obj)
498 498 if lineno is None:
499 499 self.noinfo('file', oname)
500 500 return
501 501
502 502 ofile = find_file(obj)
503 503 # run contents of file through pager starting at line where the object
504 504 # is defined, as long as the file isn't binary and is actually on the
505 505 # filesystem.
506 506 if ofile.endswith(('.so', '.dll', '.pyd')):
507 507 print('File %r is binary, not printing.' % ofile)
508 508 elif not os.path.isfile(ofile):
509 509 print('File %r does not exist, not printing.' % ofile)
510 510 else:
511 511 # Print only text files, not extension binaries. Note that
512 512 # getsourcelines returns lineno with 1-offset and page() uses
513 513 # 0-offset, so we must adjust.
514 514 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
515 515
516 516
517 517 def _mime_format(self, text:str, formatter=None) -> dict:
518 518 """Return a mime bundle representation of the input text.
519 519
520 520 - if `formatter` is None, the returned mime bundle has
521 521 a `text/plain` field, with the input text.
522 522 a `text/html` field with a `<pre>` tag containing the input text.
523 523
524 524 - if `formatter` is not None, it must be a callable transforming the
525 525 input text into a mime bundle. Default values for `text/plain` and
526 526 `text/html` representations are the ones described above.
527 527
528 528 Note:
529 529
530 530 Formatters returning strings are supported but this behavior is deprecated.
531 531
532 532 """
533 533 defaults = {
534 534 'text/plain': text,
535 535 'text/html': '<pre>' + text + '</pre>'
536 536 }
537 537
538 538 if formatter is None:
539 539 return defaults
540 540 else:
541 541 formatted = formatter(text)
542 542
543 543 if not isinstance(formatted, dict):
544 544 # Handle the deprecated behavior of a formatter returning
545 545 # a string instead of a mime bundle.
546 546 return {
547 547 'text/plain': formatted,
548 548 'text/html': '<pre>' + formatted + '</pre>'
549 549 }
550 550
551 551 else:
552 552 return dict(defaults, **formatted)
553 553
554 554
555 555 def format_mime(self, bundle):
556 556
557 557 text_plain = bundle['text/plain']
558 558
559 559 text = ''
560 560 heads, bodies = list(zip(*text_plain))
561 561 _len = max(len(h) for h in heads)
562 562
563 563 for head, body in zip(heads, bodies):
564 564 body = body.strip('\n')
565 565 delim = '\n' if '\n' in body else ' '
566 566 text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
567 567
568 568 bundle['text/plain'] = text
569 569 return bundle
570 570
571 571 def _get_info(
572 572 self, obj, oname="", formatter=None, info=None, detail_level=0, omit_sections=()
573 573 ):
574 574 """Retrieve an info dict and format it.
575 575
576 576 Parameters
577 577 ----------
578 578 obj : any
579 579 Object to inspect and return info from
580 580 oname: str (default: ''):
581 581 Name of the variable pointing to `obj`.
582 582 formatter : callable
583 583 info:
584 584 already computed information
585 585 detail_level : integer
586 586 Granularity of detail level, if set to 1, give more information.
587 587 omit_sections : container[str]
588 588 Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`)
589 589 """
590 590
591 591 info = self.info(obj, oname=oname, info=info, detail_level=detail_level)
592 592
593 593 _mime = {
594 594 'text/plain': [],
595 595 'text/html': '',
596 596 }
597 597
598 598 def append_field(bundle, title:str, key:str, formatter=None):
599 599 if title in omit_sections or key in omit_sections:
600 600 return
601 601 field = info[key]
602 602 if field is not None:
603 603 formatted_field = self._mime_format(field, formatter)
604 604 bundle['text/plain'].append((title, formatted_field['text/plain']))
605 605 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
606 606
607 607 def code_formatter(text):
608 608 return {
609 609 'text/plain': self.format(text),
610 610 'text/html': pylight(text)
611 611 }
612 612
613 613 if info['isalias']:
614 614 append_field(_mime, 'Repr', 'string_form')
615 615
616 616 elif info['ismagic']:
617 617 if detail_level > 0:
618 618 append_field(_mime, 'Source', 'source', code_formatter)
619 619 else:
620 620 append_field(_mime, 'Docstring', 'docstring', formatter)
621 621 append_field(_mime, 'File', 'file')
622 622
623 623 elif info['isclass'] or is_simple_callable(obj):
624 624 # Functions, methods, classes
625 625 append_field(_mime, 'Signature', 'definition', code_formatter)
626 626 append_field(_mime, 'Init signature', 'init_definition', code_formatter)
627 627 append_field(_mime, 'Docstring', 'docstring', formatter)
628 628 if detail_level > 0 and info['source']:
629 629 append_field(_mime, 'Source', 'source', code_formatter)
630 630 else:
631 631 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
632 632
633 633 append_field(_mime, 'File', 'file')
634 634 append_field(_mime, 'Type', 'type_name')
635 635 append_field(_mime, 'Subclasses', 'subclasses')
636 636
637 637 else:
638 638 # General Python objects
639 639 append_field(_mime, 'Signature', 'definition', code_formatter)
640 640 append_field(_mime, 'Call signature', 'call_def', code_formatter)
641 641 append_field(_mime, 'Type', 'type_name')
642 642 append_field(_mime, 'String form', 'string_form')
643 643
644 644 # Namespace
645 645 if info['namespace'] != 'Interactive':
646 646 append_field(_mime, 'Namespace', 'namespace')
647 647
648 648 append_field(_mime, 'Length', 'length')
649 649 append_field(_mime, 'File', 'file')
650 650
651 651 # Source or docstring, depending on detail level and whether
652 652 # source found.
653 653 if detail_level > 0 and info['source']:
654 654 append_field(_mime, 'Source', 'source', code_formatter)
655 655 else:
656 656 append_field(_mime, 'Docstring', 'docstring', formatter)
657 657
658 658 append_field(_mime, 'Class docstring', 'class_docstring', formatter)
659 659 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
660 660 append_field(_mime, 'Call docstring', 'call_docstring', formatter)
661 661
662 662
663 663 return self.format_mime(_mime)
664 664
665 665 def pinfo(
666 666 self,
667 667 obj,
668 668 oname="",
669 669 formatter=None,
670 670 info=None,
671 671 detail_level=0,
672 672 enable_html_pager=True,
673 673 omit_sections=(),
674 674 ):
675 675 """Show detailed information about an object.
676 676
677 677 Optional arguments:
678 678
679 679 - oname: name of the variable pointing to the object.
680 680
681 681 - formatter: callable (optional)
682 682 A special formatter for docstrings.
683 683
684 684 The formatter is a callable that takes a string as an input
685 685 and returns either a formatted string or a mime type bundle
686 686 in the form of a dictionary.
687 687
688 688 Although the support of custom formatter returning a string
689 689 instead of a mime type bundle is deprecated.
690 690
691 691 - info: a structure with some information fields which may have been
692 692 precomputed already.
693 693
694 694 - detail_level: if set to 1, more information is given.
695 695
696 696 - omit_sections: set of section keys and titles to omit
697 697 """
698 698 info = self._get_info(
699 699 obj, oname, formatter, info, detail_level, omit_sections=omit_sections
700 700 )
701 701 if not enable_html_pager:
702 702 del info['text/html']
703 703 page.page(info)
704 704
705 705 def _info(self, obj, oname="", info=None, detail_level=0):
706 706 """
707 Inspector.info() was likely unproperly marked as deprecated
707 Inspector.info() was likely improperly marked as deprecated
708 708 while only a parameter was deprecated. We "un-deprecate" it.
709 709 """
710 710
711 711 warnings.warn(
712 "The `Inspector.info()` has been un-deprecated as of 8.0 and the"
713 " `formatter=` keyword removed. `Inspector._info` is now an alias."
714 " You can always call `.info()` directly.",
712 "The `Inspector.info()` method has been un-deprecated as of 8.0 "
713 "and the `formatter=` keyword removed. `Inspector._info` is now "
714 "an alias, and you can just call `.info()` directly.",
715 715 DeprecationWarning,
716 716 stacklevel=2,
717 717 )
718 718 return self.info(obj, oname=oname, info=info, detail_level=detail_level)
719 719
720 720 def info(self, obj, oname="", info=None, detail_level=0) -> dict:
721 721 """Compute a dict with detailed information about an object.
722 722
723 723 Parameters
724 724 ----------
725 725 obj : any
726 726 An object to find information about
727 727 oname : str (default: '')
728 728 Name of the variable pointing to `obj`.
729 729 info : (default: None)
730 730 A struct (dict like with attr access) with some information fields
731 731 which may have been precomputed already.
732 732 detail_level : int (default:0)
733 733 If set to 1, more information is given.
734 734
735 735 Returns
736 736 -------
737 737 An object info dict with known fields from `info_fields`. Keys are
738 738 strings, values are string or None.
739 739 """
740 740
741 741 if info is None:
742 742 ismagic = False
743 743 isalias = False
744 744 ospace = ''
745 745 else:
746 746 ismagic = info.ismagic
747 747 isalias = info.isalias
748 748 ospace = info.namespace
749 749
750 750 # Get docstring, special-casing aliases:
751 751 if isalias:
752 752 if not callable(obj):
753 753 try:
754 754 ds = "Alias to the system command:\n %s" % obj[1]
755 755 except:
756 756 ds = "Alias: " + str(obj)
757 757 else:
758 758 ds = "Alias to " + str(obj)
759 759 if obj.__doc__:
760 760 ds += "\nDocstring:\n" + obj.__doc__
761 761 else:
762 762 ds = getdoc(obj)
763 763 if ds is None:
764 764 ds = '<no docstring>'
765 765
766 766 # store output in a dict, we initialize it here and fill it as we go
767 767 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
768 768
769 769 string_max = 200 # max size of strings to show (snipped if longer)
770 770 shalf = int((string_max - 5) / 2)
771 771
772 772 if ismagic:
773 773 out['type_name'] = 'Magic function'
774 774 elif isalias:
775 775 out['type_name'] = 'System alias'
776 776 else:
777 777 out['type_name'] = type(obj).__name__
778 778
779 779 try:
780 780 bclass = obj.__class__
781 781 out['base_class'] = str(bclass)
782 782 except:
783 783 pass
784 784
785 785 # String form, but snip if too long in ? form (full in ??)
786 786 if detail_level >= self.str_detail_level:
787 787 try:
788 788 ostr = str(obj)
789 789 str_head = 'string_form'
790 790 if not detail_level and len(ostr)>string_max:
791 791 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
792 792 ostr = ("\n" + " " * len(str_head.expandtabs())).\
793 793 join(q.strip() for q in ostr.split("\n"))
794 794 out[str_head] = ostr
795 795 except:
796 796 pass
797 797
798 798 if ospace:
799 799 out['namespace'] = ospace
800 800
801 801 # Length (for strings and lists)
802 802 try:
803 803 out['length'] = str(len(obj))
804 804 except Exception:
805 805 pass
806 806
807 807 # Filename where object was defined
808 808 binary_file = False
809 809 fname = find_file(obj)
810 810 if fname is None:
811 811 # if anything goes wrong, we don't want to show source, so it's as
812 812 # if the file was binary
813 813 binary_file = True
814 814 else:
815 815 if fname.endswith(('.so', '.dll', '.pyd')):
816 816 binary_file = True
817 817 elif fname.endswith('<string>'):
818 818 fname = 'Dynamically generated function. No source code available.'
819 819 out['file'] = compress_user(fname)
820 820
821 821 # Original source code for a callable, class or property.
822 822 if detail_level:
823 823 # Flush the source cache because inspect can return out-of-date
824 824 # source
825 825 linecache.checkcache()
826 826 try:
827 827 if isinstance(obj, property) or not binary_file:
828 828 src = getsource(obj, oname)
829 829 if src is not None:
830 830 src = src.rstrip()
831 831 out['source'] = src
832 832
833 833 except Exception:
834 834 pass
835 835
836 836 # Add docstring only if no source is to be shown (avoid repetitions).
837 837 if ds and not self._source_contains_docstring(out.get('source'), ds):
838 838 out['docstring'] = ds
839 839
840 840 # Constructor docstring for classes
841 841 if inspect.isclass(obj):
842 842 out['isclass'] = True
843 843
844 844 # get the init signature:
845 845 try:
846 846 init_def = self._getdef(obj, oname)
847 847 except AttributeError:
848 848 init_def = None
849 849
850 850 # get the __init__ docstring
851 851 try:
852 852 obj_init = obj.__init__
853 853 except AttributeError:
854 854 init_ds = None
855 855 else:
856 856 if init_def is None:
857 857 # Get signature from init if top-level sig failed.
858 858 # Can happen for built-in types (list, etc.).
859 859 try:
860 860 init_def = self._getdef(obj_init, oname)
861 861 except AttributeError:
862 862 pass
863 863 init_ds = getdoc(obj_init)
864 864 # Skip Python's auto-generated docstrings
865 865 if init_ds == _object_init_docstring:
866 866 init_ds = None
867 867
868 868 if init_def:
869 869 out['init_definition'] = init_def
870 870
871 871 if init_ds:
872 872 out['init_docstring'] = init_ds
873 873
874 874 names = [sub.__name__ for sub in type.__subclasses__(obj)]
875 875 if len(names) < 10:
876 876 all_names = ', '.join(names)
877 877 else:
878 878 all_names = ', '.join(names[:10]+['...'])
879 879 out['subclasses'] = all_names
880 880 # and class docstring for instances:
881 881 else:
882 882 # reconstruct the function definition and print it:
883 883 defln = self._getdef(obj, oname)
884 884 if defln:
885 885 out['definition'] = defln
886 886
887 887 # First, check whether the instance docstring is identical to the
888 888 # class one, and print it separately if they don't coincide. In
889 889 # most cases they will, but it's nice to print all the info for
890 890 # objects which use instance-customized docstrings.
891 891 if ds:
892 892 try:
893 893 cls = getattr(obj,'__class__')
894 894 except:
895 895 class_ds = None
896 896 else:
897 897 class_ds = getdoc(cls)
898 898 # Skip Python's auto-generated docstrings
899 899 if class_ds in _builtin_type_docstrings:
900 900 class_ds = None
901 901 if class_ds and ds != class_ds:
902 902 out['class_docstring'] = class_ds
903 903
904 904 # Next, try to show constructor docstrings
905 905 try:
906 906 init_ds = getdoc(obj.__init__)
907 907 # Skip Python's auto-generated docstrings
908 908 if init_ds == _object_init_docstring:
909 909 init_ds = None
910 910 except AttributeError:
911 911 init_ds = None
912 912 if init_ds:
913 913 out['init_docstring'] = init_ds
914 914
915 915 # Call form docstring for callable instances
916 916 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
917 917 call_def = self._getdef(obj.__call__, oname)
918 918 if call_def and (call_def != out.get('definition')):
919 919 # it may never be the case that call def and definition differ,
920 920 # but don't include the same signature twice
921 921 out['call_def'] = call_def
922 922 call_ds = getdoc(obj.__call__)
923 923 # Skip Python's auto-generated docstrings
924 924 if call_ds == _func_call_docstring:
925 925 call_ds = None
926 926 if call_ds:
927 927 out['call_docstring'] = call_ds
928 928
929 929 return object_info(**out)
930 930
931 931 @staticmethod
932 932 def _source_contains_docstring(src, doc):
933 933 """
934 934 Check whether the source *src* contains the docstring *doc*.
935 935
936 936 This is is helper function to skip displaying the docstring if the
937 937 source already contains it, avoiding repetition of information.
938 938 """
939 939 try:
940 940 def_node, = ast.parse(dedent(src)).body
941 941 return ast.get_docstring(def_node) == doc
942 942 except Exception:
943 943 # The source can become invalid or even non-existent (because it
944 944 # is re-fetched from the source file) so the above code fail in
945 945 # arbitrary ways.
946 946 return False
947 947
948 948 def psearch(self,pattern,ns_table,ns_search=[],
949 949 ignore_case=False,show_all=False, *, list_types=False):
950 950 """Search namespaces with wildcards for objects.
951 951
952 952 Arguments:
953 953
954 954 - pattern: string containing shell-like wildcards to use in namespace
955 955 searches and optionally a type specification to narrow the search to
956 956 objects of that type.
957 957
958 958 - ns_table: dict of name->namespaces for search.
959 959
960 960 Optional arguments:
961 961
962 962 - ns_search: list of namespace names to include in search.
963 963
964 964 - ignore_case(False): make the search case-insensitive.
965 965
966 966 - show_all(False): show all names, including those starting with
967 967 underscores.
968 968
969 969 - list_types(False): list all available object types for object matching.
970 970 """
971 971 #print 'ps pattern:<%r>' % pattern # dbg
972 972
973 973 # defaults
974 974 type_pattern = 'all'
975 975 filter = ''
976 976
977 977 # list all object types
978 978 if list_types:
979 979 page.page('\n'.join(sorted(typestr2type)))
980 980 return
981 981
982 982 cmds = pattern.split()
983 983 len_cmds = len(cmds)
984 984 if len_cmds == 1:
985 985 # Only filter pattern given
986 986 filter = cmds[0]
987 987 elif len_cmds == 2:
988 988 # Both filter and type specified
989 989 filter,type_pattern = cmds
990 990 else:
991 991 raise ValueError('invalid argument string for psearch: <%s>' %
992 992 pattern)
993 993
994 994 # filter search namespaces
995 995 for name in ns_search:
996 996 if name not in ns_table:
997 997 raise ValueError('invalid namespace <%s>. Valid names: %s' %
998 998 (name,ns_table.keys()))
999 999
1000 1000 #print 'type_pattern:',type_pattern # dbg
1001 1001 search_result, namespaces_seen = set(), set()
1002 1002 for ns_name in ns_search:
1003 1003 ns = ns_table[ns_name]
1004 1004 # Normally, locals and globals are the same, so we just check one.
1005 1005 if id(ns) in namespaces_seen:
1006 1006 continue
1007 1007 namespaces_seen.add(id(ns))
1008 1008 tmp_res = list_namespace(ns, type_pattern, filter,
1009 1009 ignore_case=ignore_case, show_all=show_all)
1010 1010 search_result.update(tmp_res)
1011 1011
1012 1012 page.page('\n'.join(sorted(search_result)))
1013 1013
1014 1014
1015 1015 def _render_signature(obj_signature, obj_name) -> str:
1016 1016 """
1017 1017 This was mostly taken from inspect.Signature.__str__.
1018 1018 Look there for the comments.
1019 1019 The only change is to add linebreaks when this gets too long.
1020 1020 """
1021 1021 result = []
1022 1022 pos_only = False
1023 1023 kw_only = True
1024 1024 for param in obj_signature.parameters.values():
1025 1025 if param.kind == inspect._POSITIONAL_ONLY:
1026 1026 pos_only = True
1027 1027 elif pos_only:
1028 1028 result.append('/')
1029 1029 pos_only = False
1030 1030
1031 1031 if param.kind == inspect._VAR_POSITIONAL:
1032 1032 kw_only = False
1033 1033 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1034 1034 result.append('*')
1035 1035 kw_only = False
1036 1036
1037 1037 result.append(str(param))
1038 1038
1039 1039 if pos_only:
1040 1040 result.append('/')
1041 1041
1042 1042 # add up name, parameters, braces (2), and commas
1043 1043 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1044 1044 # This doesn’t fit behind “Signature: ” in an inspect window.
1045 1045 rendered = '{}(\n{})'.format(obj_name, ''.join(
1046 1046 ' {},\n'.format(r) for r in result)
1047 1047 )
1048 1048 else:
1049 1049 rendered = '{}({})'.format(obj_name, ', '.join(result))
1050 1050
1051 1051 if obj_signature.return_annotation is not inspect._empty:
1052 1052 anno = inspect.formatannotation(obj_signature.return_annotation)
1053 1053 rendered += ' -> {}'.format(anno)
1054 1054
1055 1055 return rendered
General Comments 0
You need to be logged in to leave comments. Login now