##// END OF EJS Templates
undeprecate info...
Matthias Bussonnier -
Show More
@@ -1,1048 +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 info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
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 def info(self, obj, oname="", formatter=None, info=None, detail_level=0):
706 """DEPRECATED since 5.0. Compute a dict with detailed information about an object."""
707 if formatter is not None:
708 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
709 'is deprecated as of IPython 5.0 and will have no effects.',
710 DeprecationWarning, stacklevel=2)
711 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
705 def _info(self, obj, oname="", info=None, detail_level=0):
706 """
707 Inspector.info() was likely unproperly marked as deprecated
708 while only a parameter was deprecated. We "un-deprecate" it.
709 """
710
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.",
715 DeprecationWarning,
716 stacklevel=2,
717 )
718 return self.info(obj, oname=oname, info=info, detail_level=detail_level)
712 719
713 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
720 def info(self, obj, oname="", info=None, detail_level=0) -> dict:
714 721 """Compute a dict with detailed information about an object.
715 722
716 723 Parameters
717 724 ----------
718 725 obj : any
719 726 An object to find information about
720 727 oname : str (default: '')
721 728 Name of the variable pointing to `obj`.
722 729 info : (default: None)
723 730 A struct (dict like with attr access) with some information fields
724 731 which may have been precomputed already.
725 732 detail_level : int (default:0)
726 733 If set to 1, more information is given.
727 734
728 735 Returns
729 736 -------
730 737 An object info dict with known fields from `info_fields`. Keys are
731 738 strings, values are string or None.
732 739 """
733 740
734 741 if info is None:
735 742 ismagic = False
736 743 isalias = False
737 744 ospace = ''
738 745 else:
739 746 ismagic = info.ismagic
740 747 isalias = info.isalias
741 748 ospace = info.namespace
742 749
743 750 # Get docstring, special-casing aliases:
744 751 if isalias:
745 752 if not callable(obj):
746 753 try:
747 754 ds = "Alias to the system command:\n %s" % obj[1]
748 755 except:
749 756 ds = "Alias: " + str(obj)
750 757 else:
751 758 ds = "Alias to " + str(obj)
752 759 if obj.__doc__:
753 760 ds += "\nDocstring:\n" + obj.__doc__
754 761 else:
755 762 ds = getdoc(obj)
756 763 if ds is None:
757 764 ds = '<no docstring>'
758 765
759 766 # store output in a dict, we initialize it here and fill it as we go
760 767 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
761 768
762 769 string_max = 200 # max size of strings to show (snipped if longer)
763 770 shalf = int((string_max - 5) / 2)
764 771
765 772 if ismagic:
766 773 out['type_name'] = 'Magic function'
767 774 elif isalias:
768 775 out['type_name'] = 'System alias'
769 776 else:
770 777 out['type_name'] = type(obj).__name__
771 778
772 779 try:
773 780 bclass = obj.__class__
774 781 out['base_class'] = str(bclass)
775 782 except:
776 783 pass
777 784
778 785 # String form, but snip if too long in ? form (full in ??)
779 786 if detail_level >= self.str_detail_level:
780 787 try:
781 788 ostr = str(obj)
782 789 str_head = 'string_form'
783 790 if not detail_level and len(ostr)>string_max:
784 791 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
785 792 ostr = ("\n" + " " * len(str_head.expandtabs())).\
786 793 join(q.strip() for q in ostr.split("\n"))
787 794 out[str_head] = ostr
788 795 except:
789 796 pass
790 797
791 798 if ospace:
792 799 out['namespace'] = ospace
793 800
794 801 # Length (for strings and lists)
795 802 try:
796 803 out['length'] = str(len(obj))
797 804 except Exception:
798 805 pass
799 806
800 807 # Filename where object was defined
801 808 binary_file = False
802 809 fname = find_file(obj)
803 810 if fname is None:
804 811 # if anything goes wrong, we don't want to show source, so it's as
805 812 # if the file was binary
806 813 binary_file = True
807 814 else:
808 815 if fname.endswith(('.so', '.dll', '.pyd')):
809 816 binary_file = True
810 817 elif fname.endswith('<string>'):
811 818 fname = 'Dynamically generated function. No source code available.'
812 819 out['file'] = compress_user(fname)
813 820
814 821 # Original source code for a callable, class or property.
815 822 if detail_level:
816 823 # Flush the source cache because inspect can return out-of-date
817 824 # source
818 825 linecache.checkcache()
819 826 try:
820 827 if isinstance(obj, property) or not binary_file:
821 828 src = getsource(obj, oname)
822 829 if src is not None:
823 830 src = src.rstrip()
824 831 out['source'] = src
825 832
826 833 except Exception:
827 834 pass
828 835
829 836 # Add docstring only if no source is to be shown (avoid repetitions).
830 837 if ds and not self._source_contains_docstring(out.get('source'), ds):
831 838 out['docstring'] = ds
832 839
833 840 # Constructor docstring for classes
834 841 if inspect.isclass(obj):
835 842 out['isclass'] = True
836 843
837 844 # get the init signature:
838 845 try:
839 846 init_def = self._getdef(obj, oname)
840 847 except AttributeError:
841 848 init_def = None
842 849
843 850 # get the __init__ docstring
844 851 try:
845 852 obj_init = obj.__init__
846 853 except AttributeError:
847 854 init_ds = None
848 855 else:
849 856 if init_def is None:
850 857 # Get signature from init if top-level sig failed.
851 858 # Can happen for built-in types (list, etc.).
852 859 try:
853 860 init_def = self._getdef(obj_init, oname)
854 861 except AttributeError:
855 862 pass
856 863 init_ds = getdoc(obj_init)
857 864 # Skip Python's auto-generated docstrings
858 865 if init_ds == _object_init_docstring:
859 866 init_ds = None
860 867
861 868 if init_def:
862 869 out['init_definition'] = init_def
863 870
864 871 if init_ds:
865 872 out['init_docstring'] = init_ds
866 873
867 874 names = [sub.__name__ for sub in type.__subclasses__(obj)]
868 875 if len(names) < 10:
869 876 all_names = ', '.join(names)
870 877 else:
871 878 all_names = ', '.join(names[:10]+['...'])
872 879 out['subclasses'] = all_names
873 880 # and class docstring for instances:
874 881 else:
875 882 # reconstruct the function definition and print it:
876 883 defln = self._getdef(obj, oname)
877 884 if defln:
878 885 out['definition'] = defln
879 886
880 887 # First, check whether the instance docstring is identical to the
881 888 # class one, and print it separately if they don't coincide. In
882 889 # most cases they will, but it's nice to print all the info for
883 890 # objects which use instance-customized docstrings.
884 891 if ds:
885 892 try:
886 893 cls = getattr(obj,'__class__')
887 894 except:
888 895 class_ds = None
889 896 else:
890 897 class_ds = getdoc(cls)
891 898 # Skip Python's auto-generated docstrings
892 899 if class_ds in _builtin_type_docstrings:
893 900 class_ds = None
894 901 if class_ds and ds != class_ds:
895 902 out['class_docstring'] = class_ds
896 903
897 904 # Next, try to show constructor docstrings
898 905 try:
899 906 init_ds = getdoc(obj.__init__)
900 907 # Skip Python's auto-generated docstrings
901 908 if init_ds == _object_init_docstring:
902 909 init_ds = None
903 910 except AttributeError:
904 911 init_ds = None
905 912 if init_ds:
906 913 out['init_docstring'] = init_ds
907 914
908 915 # Call form docstring for callable instances
909 916 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
910 917 call_def = self._getdef(obj.__call__, oname)
911 918 if call_def and (call_def != out.get('definition')):
912 919 # it may never be the case that call def and definition differ,
913 920 # but don't include the same signature twice
914 921 out['call_def'] = call_def
915 922 call_ds = getdoc(obj.__call__)
916 923 # Skip Python's auto-generated docstrings
917 924 if call_ds == _func_call_docstring:
918 925 call_ds = None
919 926 if call_ds:
920 927 out['call_docstring'] = call_ds
921 928
922 929 return object_info(**out)
923 930
924 931 @staticmethod
925 932 def _source_contains_docstring(src, doc):
926 933 """
927 934 Check whether the source *src* contains the docstring *doc*.
928 935
929 936 This is is helper function to skip displaying the docstring if the
930 937 source already contains it, avoiding repetition of information.
931 938 """
932 939 try:
933 940 def_node, = ast.parse(dedent(src)).body
934 941 return ast.get_docstring(def_node) == doc
935 942 except Exception:
936 943 # The source can become invalid or even non-existent (because it
937 944 # is re-fetched from the source file) so the above code fail in
938 945 # arbitrary ways.
939 946 return False
940 947
941 948 def psearch(self,pattern,ns_table,ns_search=[],
942 949 ignore_case=False,show_all=False, *, list_types=False):
943 950 """Search namespaces with wildcards for objects.
944 951
945 952 Arguments:
946 953
947 954 - pattern: string containing shell-like wildcards to use in namespace
948 955 searches and optionally a type specification to narrow the search to
949 956 objects of that type.
950 957
951 958 - ns_table: dict of name->namespaces for search.
952 959
953 960 Optional arguments:
954 961
955 962 - ns_search: list of namespace names to include in search.
956 963
957 964 - ignore_case(False): make the search case-insensitive.
958 965
959 966 - show_all(False): show all names, including those starting with
960 967 underscores.
961 968
962 969 - list_types(False): list all available object types for object matching.
963 970 """
964 971 #print 'ps pattern:<%r>' % pattern # dbg
965 972
966 973 # defaults
967 974 type_pattern = 'all'
968 975 filter = ''
969 976
970 977 # list all object types
971 978 if list_types:
972 979 page.page('\n'.join(sorted(typestr2type)))
973 980 return
974 981
975 982 cmds = pattern.split()
976 983 len_cmds = len(cmds)
977 984 if len_cmds == 1:
978 985 # Only filter pattern given
979 986 filter = cmds[0]
980 987 elif len_cmds == 2:
981 988 # Both filter and type specified
982 989 filter,type_pattern = cmds
983 990 else:
984 991 raise ValueError('invalid argument string for psearch: <%s>' %
985 992 pattern)
986 993
987 994 # filter search namespaces
988 995 for name in ns_search:
989 996 if name not in ns_table:
990 997 raise ValueError('invalid namespace <%s>. Valid names: %s' %
991 998 (name,ns_table.keys()))
992 999
993 1000 #print 'type_pattern:',type_pattern # dbg
994 1001 search_result, namespaces_seen = set(), set()
995 1002 for ns_name in ns_search:
996 1003 ns = ns_table[ns_name]
997 1004 # Normally, locals and globals are the same, so we just check one.
998 1005 if id(ns) in namespaces_seen:
999 1006 continue
1000 1007 namespaces_seen.add(id(ns))
1001 1008 tmp_res = list_namespace(ns, type_pattern, filter,
1002 1009 ignore_case=ignore_case, show_all=show_all)
1003 1010 search_result.update(tmp_res)
1004 1011
1005 1012 page.page('\n'.join(sorted(search_result)))
1006 1013
1007 1014
1008 1015 def _render_signature(obj_signature, obj_name) -> str:
1009 1016 """
1010 1017 This was mostly taken from inspect.Signature.__str__.
1011 1018 Look there for the comments.
1012 1019 The only change is to add linebreaks when this gets too long.
1013 1020 """
1014 1021 result = []
1015 1022 pos_only = False
1016 1023 kw_only = True
1017 1024 for param in obj_signature.parameters.values():
1018 1025 if param.kind == inspect._POSITIONAL_ONLY:
1019 1026 pos_only = True
1020 1027 elif pos_only:
1021 1028 result.append('/')
1022 1029 pos_only = False
1023 1030
1024 1031 if param.kind == inspect._VAR_POSITIONAL:
1025 1032 kw_only = False
1026 1033 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1027 1034 result.append('*')
1028 1035 kw_only = False
1029 1036
1030 1037 result.append(str(param))
1031 1038
1032 1039 if pos_only:
1033 1040 result.append('/')
1034 1041
1035 1042 # add up name, parameters, braces (2), and commas
1036 1043 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1037 1044 # This doesn’t fit behind “Signature: ” in an inspect window.
1038 1045 rendered = '{}(\n{})'.format(obj_name, ''.join(
1039 1046 ' {},\n'.format(r) for r in result)
1040 1047 )
1041 1048 else:
1042 1049 rendered = '{}({})'.format(obj_name, ', '.join(result))
1043 1050
1044 1051 if obj_signature.return_annotation is not inspect._empty:
1045 1052 anno = inspect.formatannotation(obj_signature.return_annotation)
1046 1053 rendered += ' -> {}'.format(anno)
1047 1054
1048 1055 return rendered
General Comments 0
You need to be logged in to leave comments. Login now