##// END OF EJS Templates
Merge pull request #12017 from Carreau/cast_cleanup_II...
Matthias Bussonnier -
r25340:88a02754 merge
parent child Browse files
Show More
@@ -1,1031 +1,1032 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 from itertools import zip_longest
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 infodict = dict(zip_longest(info_fields, [None]))
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 if hasattr(obj, '__class__'):
186 186 try:
187 187 src = inspect.getsource(obj.__class__)
188 188 except TypeError:
189 189 return None
190 190
191 191 return src
192 192
193 193
194 194 def is_simple_callable(obj):
195 195 """True if obj is a function ()"""
196 196 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
197 197 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
198 198
199 199 @undoc
200 200 def getargspec(obj):
201 201 """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
202 202 :func:inspect.getargspec` on Python 2.
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: 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. Extract call tip data from an oinfo dict.
238 238 """
239 239 warnings.warn('`call_tip` function is deprecated as of IPython 6.0'
240 240 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
241 241 # Get call definition
242 242 argspec = oinfo.get('argspec')
243 243 if argspec is None:
244 244 call_line = None
245 245 else:
246 246 # Callable objects will have 'self' as their first argument, prune
247 247 # it out if it's there for clarity (since users do *not* pass an
248 248 # extra first argument explicitly).
249 249 try:
250 250 has_self = argspec['args'][0] == 'self'
251 251 except (KeyError, IndexError):
252 252 pass
253 253 else:
254 254 if has_self:
255 255 argspec['args'] = argspec['args'][1:]
256 256
257 257 call_line = oinfo['name']+format_argspec(argspec)
258 258
259 259 # Now get docstring.
260 260 # The priority is: call docstring, constructor docstring, main one.
261 261 doc = oinfo.get('call_docstring')
262 262 if doc is None:
263 263 doc = oinfo.get('init_docstring')
264 264 if doc is None:
265 265 doc = oinfo.get('docstring','')
266 266
267 267 return call_line, doc
268 268
269 269
270 270 def _get_wrapped(obj):
271 271 """Get the original object if wrapped in one or more @decorators
272 272
273 273 Some objects automatically construct similar objects on any unrecognised
274 274 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
275 275 this will arbitrarily cut off after 100 levels of obj.__wrapped__
276 276 attribute access. --TK, Jan 2016
277 277 """
278 278 orig_obj = obj
279 279 i = 0
280 280 while safe_hasattr(obj, '__wrapped__'):
281 281 obj = obj.__wrapped__
282 282 i += 1
283 283 if i > 100:
284 284 # __wrapped__ is probably a lie, so return the thing we started with
285 285 return orig_obj
286 286 return obj
287 287
288 288 def find_file(obj) -> str:
289 289 """Find the absolute path to the file where an object was defined.
290 290
291 291 This is essentially a robust wrapper around `inspect.getabsfile`.
292 292
293 293 Returns None if no file can be found.
294 294
295 295 Parameters
296 296 ----------
297 297 obj : any Python object
298 298
299 299 Returns
300 300 -------
301 301 fname : str
302 302 The absolute path to the file where the object was defined.
303 303 """
304 304 obj = _get_wrapped(obj)
305 305
306 306 fname = None
307 307 try:
308 308 fname = inspect.getabsfile(obj)
309 309 except TypeError:
310 310 # For an instance, the file that matters is where its class was
311 311 # declared.
312 312 if hasattr(obj, '__class__'):
313 313 try:
314 314 fname = inspect.getabsfile(obj.__class__)
315 315 except TypeError:
316 316 # Can happen for builtins
317 317 pass
318 318 except:
319 319 pass
320 320 return cast_unicode(fname)
321 321
322 322
323 323 def find_source_lines(obj):
324 324 """Find the line number in a file where an object was defined.
325 325
326 326 This is essentially a robust wrapper around `inspect.getsourcelines`.
327 327
328 328 Returns None if no file can be found.
329 329
330 330 Parameters
331 331 ----------
332 332 obj : any Python object
333 333
334 334 Returns
335 335 -------
336 336 lineno : int
337 337 The line number where the object definition starts.
338 338 """
339 339 obj = _get_wrapped(obj)
340 340
341 341 try:
342 342 try:
343 343 lineno = inspect.getsourcelines(obj)[1]
344 344 except TypeError:
345 345 # For instances, try the class object like getsource() does
346 346 if hasattr(obj, '__class__'):
347 347 lineno = inspect.getsourcelines(obj.__class__)[1]
348 348 else:
349 349 lineno = None
350 350 except:
351 351 return None
352 352
353 353 return lineno
354 354
355 355 class Inspector(Colorable):
356 356
357 357 def __init__(self, color_table=InspectColors,
358 358 code_color_table=PyColorize.ANSICodeColors,
359 359 scheme=None,
360 360 str_detail_level=0,
361 361 parent=None, config=None):
362 362 super(Inspector, self).__init__(parent=parent, config=config)
363 363 self.color_table = color_table
364 364 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
365 365 self.format = self.parser.format
366 366 self.str_detail_level = str_detail_level
367 367 self.set_active_scheme(scheme)
368 368
369 369 def _getdef(self,obj,oname='') -> Union[str,None]:
370 370 """Return the call signature for any callable object.
371 371
372 372 If any exception is generated, None is returned instead and the
373 373 exception is suppressed."""
374 374 try:
375 375 return _render_signature(signature(obj), oname)
376 376 except:
377 377 return None
378 378
379 379 def __head(self,h) -> str:
380 380 """Return a header string with proper colors."""
381 381 return '%s%s%s' % (self.color_table.active_colors.header,h,
382 382 self.color_table.active_colors.normal)
383 383
384 384 def set_active_scheme(self, scheme):
385 385 if scheme is not None:
386 386 self.color_table.set_active_scheme(scheme)
387 387 self.parser.color_table.set_active_scheme(scheme)
388 388
389 389 def noinfo(self, msg, oname):
390 390 """Generic message when no information is found."""
391 391 print('No %s found' % msg, end=' ')
392 392 if oname:
393 393 print('for %s' % oname)
394 394 else:
395 395 print()
396 396
397 397 def pdef(self, obj, oname=''):
398 398 """Print the call signature for any callable object.
399 399
400 400 If the object is a class, print the constructor information."""
401 401
402 402 if not callable(obj):
403 403 print('Object is not callable.')
404 404 return
405 405
406 406 header = ''
407 407
408 408 if inspect.isclass(obj):
409 409 header = self.__head('Class constructor information:\n')
410 410
411 411
412 412 output = self._getdef(obj,oname)
413 413 if output is None:
414 414 self.noinfo('definition header',oname)
415 415 else:
416 416 print(header,self.format(output), end=' ')
417 417
418 418 # In Python 3, all classes are new-style, so they all have __init__.
419 419 @skip_doctest
420 420 def pdoc(self, obj, oname='', formatter=None):
421 421 """Print the docstring for any object.
422 422
423 423 Optional:
424 424 -formatter: a function to run the docstring through for specially
425 425 formatted docstrings.
426 426
427 427 Examples
428 428 --------
429 429
430 430 In [1]: class NoInit:
431 431 ...: pass
432 432
433 433 In [2]: class NoDoc:
434 434 ...: def __init__(self):
435 435 ...: pass
436 436
437 437 In [3]: %pdoc NoDoc
438 438 No documentation found for NoDoc
439 439
440 440 In [4]: %pdoc NoInit
441 441 No documentation found for NoInit
442 442
443 443 In [5]: obj = NoInit()
444 444
445 445 In [6]: %pdoc obj
446 446 No documentation found for obj
447 447
448 448 In [5]: obj2 = NoDoc()
449 449
450 450 In [6]: %pdoc obj2
451 451 No documentation found for obj2
452 452 """
453 453
454 454 head = self.__head # For convenience
455 455 lines = []
456 456 ds = getdoc(obj)
457 457 if formatter:
458 458 ds = formatter(ds).get('plain/text', ds)
459 459 if ds:
460 460 lines.append(head("Class docstring:"))
461 461 lines.append(indent(ds))
462 462 if inspect.isclass(obj) and hasattr(obj, '__init__'):
463 463 init_ds = getdoc(obj.__init__)
464 464 if init_ds is not None:
465 465 lines.append(head("Init docstring:"))
466 466 lines.append(indent(init_ds))
467 467 elif hasattr(obj,'__call__'):
468 468 call_ds = getdoc(obj.__call__)
469 469 if call_ds:
470 470 lines.append(head("Call docstring:"))
471 471 lines.append(indent(call_ds))
472 472
473 473 if not lines:
474 474 self.noinfo('documentation',oname)
475 475 else:
476 476 page.page('\n'.join(lines))
477 477
478 478 def psource(self, obj, oname=''):
479 479 """Print the source code for an object."""
480 480
481 481 # Flush the source cache because inspect can return out-of-date source
482 482 linecache.checkcache()
483 483 try:
484 484 src = getsource(obj, oname=oname)
485 485 except Exception:
486 486 src = None
487 487
488 488 if src is None:
489 489 self.noinfo('source', oname)
490 490 else:
491 491 page.page(self.format(src))
492 492
493 493 def pfile(self, obj, oname=''):
494 494 """Show the whole file where an object was defined."""
495 495
496 496 lineno = find_source_lines(obj)
497 497 if lineno is None:
498 498 self.noinfo('file', oname)
499 499 return
500 500
501 501 ofile = find_file(obj)
502 502 # run contents of file through pager starting at line where the object
503 503 # is defined, as long as the file isn't binary and is actually on the
504 504 # filesystem.
505 505 if ofile.endswith(('.so', '.dll', '.pyd')):
506 506 print('File %r is binary, not printing.' % ofile)
507 507 elif not os.path.isfile(ofile):
508 508 print('File %r does not exist, not printing.' % ofile)
509 509 else:
510 510 # Print only text files, not extension binaries. Note that
511 511 # getsourcelines returns lineno with 1-offset and page() uses
512 512 # 0-offset, so we must adjust.
513 513 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
514 514
515 def _mime_format(self, text, formatter=None):
515
516 def _mime_format(self, text:str, formatter=None) -> dict:
516 517 """Return a mime bundle representation of the input text.
517 518
518 519 - if `formatter` is None, the returned mime bundle has
519 520 a `text/plain` field, with the input text.
520 521 a `text/html` field with a `<pre>` tag containing the input text.
521 522
522 523 - if `formatter` is not None, it must be a callable transforming the
523 524 input text into a mime bundle. Default values for `text/plain` and
524 525 `text/html` representations are the ones described above.
525 526
526 527 Note:
527 528
528 529 Formatters returning strings are supported but this behavior is deprecated.
529 530
530 531 """
531 text = cast_unicode(text)
532 532 defaults = {
533 533 'text/plain': text,
534 534 'text/html': '<pre>' + text + '</pre>'
535 535 }
536 536
537 537 if formatter is None:
538 538 return defaults
539 539 else:
540 540 formatted = formatter(text)
541 541
542 542 if not isinstance(formatted, dict):
543 543 # Handle the deprecated behavior of a formatter returning
544 544 # a string instead of a mime bundle.
545 545 return {
546 546 'text/plain': formatted,
547 547 'text/html': '<pre>' + formatted + '</pre>'
548 548 }
549 549
550 550 else:
551 551 return dict(defaults, **formatted)
552 552
553 553
554 554 def format_mime(self, bundle):
555 555
556 556 text_plain = bundle['text/plain']
557 557
558 558 text = ''
559 559 heads, bodies = list(zip(*text_plain))
560 560 _len = max(len(h) for h in heads)
561 561
562 562 for head, body in zip(heads, bodies):
563 563 body = body.strip('\n')
564 564 delim = '\n' if '\n' in body else ' '
565 565 text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
566 566
567 567 bundle['text/plain'] = text
568 568 return bundle
569 569
570 570 def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
571 571 """Retrieve an info dict and format it.
572 572
573 573 Parameters
574 574 ==========
575 575
576 576 obj: any
577 577 Object to inspect and return info from
578 578 oname: str (default: ''):
579 579 Name of the variable pointing to `obj`.
580 580 formatter: callable
581 581 info:
582 582 already computed information
583 583 detail_level: integer
584 584 Granularity of detail level, if set to 1, give more information.
585 585 """
586 586
587 587 info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
588 588
589 589 _mime = {
590 590 'text/plain': [],
591 591 'text/html': '',
592 592 }
593 593
594 def append_field(bundle, title, key, formatter=None):
594 def append_field(bundle, title:str, key:str, formatter=None):
595 595 field = info[key]
596 596 if field is not None:
597 597 formatted_field = self._mime_format(field, formatter)
598 598 bundle['text/plain'].append((title, formatted_field['text/plain']))
599 599 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
600 600
601 601 def code_formatter(text):
602 602 return {
603 603 'text/plain': self.format(text),
604 604 'text/html': pylight(text)
605 605 }
606 606
607 607 if info['isalias']:
608 608 append_field(_mime, 'Repr', 'string_form')
609 609
610 610 elif info['ismagic']:
611 611 if detail_level > 0:
612 612 append_field(_mime, 'Source', 'source', code_formatter)
613 613 else:
614 614 append_field(_mime, 'Docstring', 'docstring', formatter)
615 615 append_field(_mime, 'File', 'file')
616 616
617 617 elif info['isclass'] or is_simple_callable(obj):
618 618 # Functions, methods, classes
619 619 append_field(_mime, 'Signature', 'definition', code_formatter)
620 620 append_field(_mime, 'Init signature', 'init_definition', code_formatter)
621 621 append_field(_mime, 'Docstring', 'docstring', formatter)
622 622 if detail_level > 0 and info['source']:
623 623 append_field(_mime, 'Source', 'source', code_formatter)
624 624 else:
625 625 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
626 626
627 627 append_field(_mime, 'File', 'file')
628 628 append_field(_mime, 'Type', 'type_name')
629 629 append_field(_mime, 'Subclasses', 'subclasses')
630 630
631 631 else:
632 632 # General Python objects
633 633 append_field(_mime, 'Signature', 'definition', code_formatter)
634 634 append_field(_mime, 'Call signature', 'call_def', code_formatter)
635 635 append_field(_mime, 'Type', 'type_name')
636 636 append_field(_mime, 'String form', 'string_form')
637 637
638 638 # Namespace
639 639 if info['namespace'] != 'Interactive':
640 640 append_field(_mime, 'Namespace', 'namespace')
641 641
642 642 append_field(_mime, 'Length', 'length')
643 643 append_field(_mime, 'File', 'file')
644 644
645 645 # Source or docstring, depending on detail level and whether
646 646 # source found.
647 647 if detail_level > 0 and info['source']:
648 648 append_field(_mime, 'Source', 'source', code_formatter)
649 649 else:
650 650 append_field(_mime, 'Docstring', 'docstring', formatter)
651 651
652 652 append_field(_mime, 'Class docstring', 'class_docstring', formatter)
653 653 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
654 654 append_field(_mime, 'Call docstring', 'call_docstring', formatter)
655 655
656 656
657 657 return self.format_mime(_mime)
658 658
659 659 def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
660 660 """Show detailed information about an object.
661 661
662 662 Optional arguments:
663 663
664 664 - oname: name of the variable pointing to the object.
665 665
666 666 - formatter: callable (optional)
667 667 A special formatter for docstrings.
668 668
669 669 The formatter is a callable that takes a string as an input
670 670 and returns either a formatted string or a mime type bundle
671 671 in the form of a dictionary.
672 672
673 673 Although the support of custom formatter returning a string
674 674 instead of a mime type bundle is deprecated.
675 675
676 676 - info: a structure with some information fields which may have been
677 677 precomputed already.
678 678
679 679 - detail_level: if set to 1, more information is given.
680 680 """
681 681 info = self._get_info(obj, oname, formatter, info, detail_level)
682 682 if not enable_html_pager:
683 683 del info['text/html']
684 684 page.page(info)
685 685
686 686 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
687 687 """DEPRECATED. Compute a dict with detailed information about an object.
688 688 """
689 689 if formatter is not None:
690 690 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
691 691 'is deprecated as of IPython 5.0 and will have no effects.',
692 692 DeprecationWarning, stacklevel=2)
693 693 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
694 694
695 695 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
696 696 """Compute a dict with detailed information about an object.
697 697
698 698 Parameters
699 699 ==========
700 700
701 701 obj: any
702 702 An object to find information about
703 703 oname: str (default: ''):
704 704 Name of the variable pointing to `obj`.
705 705 info: (default: None)
706 706 A struct (dict like with attr access) with some information fields
707 707 which may have been precomputed already.
708 708 detail_level: int (default:0)
709 709 If set to 1, more information is given.
710 710
711 711 Returns
712 712 =======
713 713
714 An object info dict with known fields from `info_fields`.
714 An object info dict with known fields from `info_fields`. Keys are
715 strings, values are string or None.
715 716 """
716 717
717 718 if info is None:
718 719 ismagic = False
719 720 isalias = False
720 721 ospace = ''
721 722 else:
722 723 ismagic = info.ismagic
723 724 isalias = info.isalias
724 725 ospace = info.namespace
725 726
726 727 # Get docstring, special-casing aliases:
727 728 if isalias:
728 729 if not callable(obj):
729 730 try:
730 731 ds = "Alias to the system command:\n %s" % obj[1]
731 732 except:
732 733 ds = "Alias: " + str(obj)
733 734 else:
734 735 ds = "Alias to " + str(obj)
735 736 if obj.__doc__:
736 737 ds += "\nDocstring:\n" + obj.__doc__
737 738 else:
738 739 ds = getdoc(obj)
739 740 if ds is None:
740 741 ds = '<no docstring>'
741 742
742 743 # store output in a dict, we initialize it here and fill it as we go
743 744 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
744 745
745 746 string_max = 200 # max size of strings to show (snipped if longer)
746 747 shalf = int((string_max - 5) / 2)
747 748
748 749 if ismagic:
749 750 out['type_name'] = 'Magic function'
750 751 elif isalias:
751 752 out['type_name'] = 'System alias'
752 753 else:
753 754 out['type_name'] = type(obj).__name__
754 755
755 756 try:
756 757 bclass = obj.__class__
757 758 out['base_class'] = str(bclass)
758 759 except:
759 760 pass
760 761
761 762 # String form, but snip if too long in ? form (full in ??)
762 763 if detail_level >= self.str_detail_level:
763 764 try:
764 765 ostr = str(obj)
765 766 str_head = 'string_form'
766 767 if not detail_level and len(ostr)>string_max:
767 768 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
768 769 ostr = ("\n" + " " * len(str_head.expandtabs())).\
769 770 join(q.strip() for q in ostr.split("\n"))
770 771 out[str_head] = ostr
771 772 except:
772 773 pass
773 774
774 775 if ospace:
775 776 out['namespace'] = ospace
776 777
777 778 # Length (for strings and lists)
778 779 try:
779 780 out['length'] = str(len(obj))
780 781 except Exception:
781 782 pass
782 783
783 784 # Filename where object was defined
784 785 binary_file = False
785 786 fname = find_file(obj)
786 787 if fname is None:
787 788 # if anything goes wrong, we don't want to show source, so it's as
788 789 # if the file was binary
789 790 binary_file = True
790 791 else:
791 792 if fname.endswith(('.so', '.dll', '.pyd')):
792 793 binary_file = True
793 794 elif fname.endswith('<string>'):
794 795 fname = 'Dynamically generated function. No source code available.'
795 796 out['file'] = compress_user(fname)
796 797
797 798 # Original source code for a callable, class or property.
798 799 if detail_level:
799 800 # Flush the source cache because inspect can return out-of-date
800 801 # source
801 802 linecache.checkcache()
802 803 try:
803 804 if isinstance(obj, property) or not binary_file:
804 805 src = getsource(obj, oname)
805 806 if src is not None:
806 807 src = src.rstrip()
807 808 out['source'] = src
808 809
809 810 except Exception:
810 811 pass
811 812
812 813 # Add docstring only if no source is to be shown (avoid repetitions).
813 814 if ds and not self._source_contains_docstring(out.get('source'), ds):
814 815 out['docstring'] = ds
815 816
816 817 # Constructor docstring for classes
817 818 if inspect.isclass(obj):
818 819 out['isclass'] = True
819 820
820 821 # get the init signature:
821 822 try:
822 823 init_def = self._getdef(obj, oname)
823 824 except AttributeError:
824 825 init_def = None
825 826
826 827 # get the __init__ docstring
827 828 try:
828 829 obj_init = obj.__init__
829 830 except AttributeError:
830 831 init_ds = None
831 832 else:
832 833 if init_def is None:
833 834 # Get signature from init if top-level sig failed.
834 835 # Can happen for built-in types (list, etc.).
835 836 try:
836 837 init_def = self._getdef(obj_init, oname)
837 838 except AttributeError:
838 839 pass
839 840 init_ds = getdoc(obj_init)
840 841 # Skip Python's auto-generated docstrings
841 842 if init_ds == _object_init_docstring:
842 843 init_ds = None
843 844
844 845 if init_def:
845 846 out['init_definition'] = init_def
846 847
847 848 if init_ds:
848 849 out['init_docstring'] = init_ds
849 850
850 851 names = [sub.__name__ for sub in type.__subclasses__(obj)]
851 852 if len(names) < 10:
852 853 all_names = ', '.join(names)
853 854 else:
854 855 all_names = ', '.join(names[:10]+['...'])
855 856 out['subclasses'] = all_names
856 857 # and class docstring for instances:
857 858 else:
858 859 # reconstruct the function definition and print it:
859 860 defln = self._getdef(obj, oname)
860 861 if defln:
861 862 out['definition'] = defln
862 863
863 864 # First, check whether the instance docstring is identical to the
864 865 # class one, and print it separately if they don't coincide. In
865 866 # most cases they will, but it's nice to print all the info for
866 867 # objects which use instance-customized docstrings.
867 868 if ds:
868 869 try:
869 870 cls = getattr(obj,'__class__')
870 871 except:
871 872 class_ds = None
872 873 else:
873 874 class_ds = getdoc(cls)
874 875 # Skip Python's auto-generated docstrings
875 876 if class_ds in _builtin_type_docstrings:
876 877 class_ds = None
877 878 if class_ds and ds != class_ds:
878 879 out['class_docstring'] = class_ds
879 880
880 881 # Next, try to show constructor docstrings
881 882 try:
882 883 init_ds = getdoc(obj.__init__)
883 884 # Skip Python's auto-generated docstrings
884 885 if init_ds == _object_init_docstring:
885 886 init_ds = None
886 887 except AttributeError:
887 888 init_ds = None
888 889 if init_ds:
889 890 out['init_docstring'] = init_ds
890 891
891 892 # Call form docstring for callable instances
892 893 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
893 894 call_def = self._getdef(obj.__call__, oname)
894 895 if call_def and (call_def != out.get('definition')):
895 896 # it may never be the case that call def and definition differ,
896 897 # but don't include the same signature twice
897 898 out['call_def'] = call_def
898 899 call_ds = getdoc(obj.__call__)
899 900 # Skip Python's auto-generated docstrings
900 901 if call_ds == _func_call_docstring:
901 902 call_ds = None
902 903 if call_ds:
903 904 out['call_docstring'] = call_ds
904 905
905 906 return object_info(**out)
906 907
907 908 @staticmethod
908 909 def _source_contains_docstring(src, doc):
909 910 """
910 911 Check whether the source *src* contains the docstring *doc*.
911 912
912 913 This is is helper function to skip displaying the docstring if the
913 914 source already contains it, avoiding repetition of information.
914 915 """
915 916 try:
916 917 def_node, = ast.parse(dedent(src)).body
917 918 return ast.get_docstring(def_node) == doc
918 919 except Exception:
919 920 # The source can become invalid or even non-existent (because it
920 921 # is re-fetched from the source file) so the above code fail in
921 922 # arbitrary ways.
922 923 return False
923 924
924 925 def psearch(self,pattern,ns_table,ns_search=[],
925 926 ignore_case=False,show_all=False, *, list_types=False):
926 927 """Search namespaces with wildcards for objects.
927 928
928 929 Arguments:
929 930
930 931 - pattern: string containing shell-like wildcards to use in namespace
931 932 searches and optionally a type specification to narrow the search to
932 933 objects of that type.
933 934
934 935 - ns_table: dict of name->namespaces for search.
935 936
936 937 Optional arguments:
937 938
938 939 - ns_search: list of namespace names to include in search.
939 940
940 941 - ignore_case(False): make the search case-insensitive.
941 942
942 943 - show_all(False): show all names, including those starting with
943 944 underscores.
944 945
945 946 - list_types(False): list all available object types for object matching.
946 947 """
947 948 #print 'ps pattern:<%r>' % pattern # dbg
948 949
949 950 # defaults
950 951 type_pattern = 'all'
951 952 filter = ''
952 953
953 954 # list all object types
954 955 if list_types:
955 956 page.page('\n'.join(sorted(typestr2type)))
956 957 return
957 958
958 959 cmds = pattern.split()
959 960 len_cmds = len(cmds)
960 961 if len_cmds == 1:
961 962 # Only filter pattern given
962 963 filter = cmds[0]
963 964 elif len_cmds == 2:
964 965 # Both filter and type specified
965 966 filter,type_pattern = cmds
966 967 else:
967 968 raise ValueError('invalid argument string for psearch: <%s>' %
968 969 pattern)
969 970
970 971 # filter search namespaces
971 972 for name in ns_search:
972 973 if name not in ns_table:
973 974 raise ValueError('invalid namespace <%s>. Valid names: %s' %
974 975 (name,ns_table.keys()))
975 976
976 977 #print 'type_pattern:',type_pattern # dbg
977 978 search_result, namespaces_seen = set(), set()
978 979 for ns_name in ns_search:
979 980 ns = ns_table[ns_name]
980 981 # Normally, locals and globals are the same, so we just check one.
981 982 if id(ns) in namespaces_seen:
982 983 continue
983 984 namespaces_seen.add(id(ns))
984 985 tmp_res = list_namespace(ns, type_pattern, filter,
985 986 ignore_case=ignore_case, show_all=show_all)
986 987 search_result.update(tmp_res)
987 988
988 989 page.page('\n'.join(sorted(search_result)))
989 990
990 991
991 992 def _render_signature(obj_signature, obj_name) -> str:
992 993 """
993 994 This was mostly taken from inspect.Signature.__str__.
994 995 Look there for the comments.
995 996 The only change is to add linebreaks when this gets too long.
996 997 """
997 998 result = []
998 999 pos_only = False
999 1000 kw_only = True
1000 1001 for param in obj_signature.parameters.values():
1001 1002 if param.kind == inspect._POSITIONAL_ONLY:
1002 1003 pos_only = True
1003 1004 elif pos_only:
1004 1005 result.append('/')
1005 1006 pos_only = False
1006 1007
1007 1008 if param.kind == inspect._VAR_POSITIONAL:
1008 1009 kw_only = False
1009 1010 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1010 1011 result.append('*')
1011 1012 kw_only = False
1012 1013
1013 1014 result.append(str(param))
1014 1015
1015 1016 if pos_only:
1016 1017 result.append('/')
1017 1018
1018 1019 # add up name, parameters, braces (2), and commas
1019 1020 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1020 1021 # This doesn’t fit behind “Signature: ” in an inspect window.
1021 1022 rendered = '{}(\n{})'.format(obj_name, ''.join(
1022 1023 ' {},\n'.format(r) for r in result)
1023 1024 )
1024 1025 else:
1025 1026 rendered = '{}({})'.format(obj_name, ', '.join(result))
1026 1027
1027 1028 if obj_signature.return_annotation is not inspect._empty:
1028 1029 anno = inspect.formatannotation(obj_signature.return_annotation)
1029 1030 rendered += ' -> {}'.format(anno)
1030 1031
1031 1032 return rendered
General Comments 0
You need to be logged in to leave comments. Login now