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