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