oinspect.py 34 KB

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