##// END OF EJS Templates
Merge pull request #13213 from Kojoley/fix-bunch-of-doctests...
Merge pull request #13213 from Kojoley/fix-bunch-of-doctests Fix bunch of doctests

File last commit:

r25450:5618e599
r26940:32497c8d merge
Show More
oinspect.py
1031 lines | 34.4 KiB | text/x-python | PythonLexer
Ville M. Vainio
crlf -> lf
r1032 # -*- coding: utf-8 -*-
"""Tools for inspecting Python objects.
Uses syntax highlighting for presenting the various information elements.
Similar in spirit to the inspect module, but all calls take a name argument to
reference the name under which an object is being read.
"""
MinRK
add object_inspect_text...
r16579 # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
Ville M. Vainio
crlf -> lf
r1032 __all__ = ['Inspector','InspectColors']
# stdlib modules
Antony Lee
In obj??, display the docstring if it is not in the source....
r24118 import ast
Ville M. Vainio
crlf -> lf
r1032 import inspect
Min RK
deprecate IPython.utils.signatures...
r23020 from inspect import signature
Ville M. Vainio
crlf -> lf
r1032 import linecache
Sylvain Corlay
Add deprecation warning
r22462 import warnings
Ville M. Vainio
crlf -> lf
r1032 import os
immerrr
Print sources for property fget/fset/fdel methods...
r17023 from textwrap import dedent
Fernando Perez
Make our fixed-up getargspec a top-level function....
r1413 import types
Jörgen Stenarson
Unicode fix for docstrings in pinfo magic...
r8322 import io as stdlib_io
Matthias Bussonnier
cast_unicode code simplification....
r25338
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 from typing import Union
Fernando Perez
Make our fixed-up getargspec a top-level function....
r1413
Ville M. Vainio
crlf -> lf
r1032 # IPython's own
Brian Granger
Paging using payloads now works.
r2830 from IPython.core import page
immerrr
Print sources for property fget/fset/fdel methods...
r17023 from IPython.lib.pretty import pretty
Paul Ivanov
fix oinspect module
r22961 from IPython.testing.skipdoctest import skip_doctest
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 from IPython.utils import PyColorize
Jörgen Stenarson
merge functionality in io and openpy relating to encoding...
r8304 from IPython.utils import openpy
Thomas Kluyver
Improvements in the code that breaks up user input.
r4744 from IPython.utils import py3compat
Jeffrey Tratner
Use safe_hasattr in dir2...
r12965 from IPython.utils.dir2 import safe_hasattr
Thomas Kluyver
Collapse user home directory to ~ in info filename
r20569 from IPython.utils.path import compress_user
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 from IPython.utils.text import indent
Brian Granger
wildcard.py => utils/wildcard.py and updated imports.
r2051 from IPython.utils.wildcard import list_namespace
Andreas
Added support to list available object types, to use on object type matching in magic function %psearch.
r24996 from IPython.utils.wildcard import typestr2type
Thomas Kluyver
Fix the display of functions with keyword-only arguments on Python 3.
r15335 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
Srinivas Reddy Thatiparthy
remove PY3 var
r23086 from IPython.utils.py3compat import cast_unicode
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109 from IPython.utils.colorable import Colorable
Srinivas Reddy Thatiparthy
This commit,...
r23035 from IPython.utils.decorators import undoc
Ville M. Vainio
crlf -> lf
r1032
Matthias Bussonnier
Some docs
r22492 from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
def pylight(code):
return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
MinRK
detect builtin docstrings in oinspect...
r14835 # builtin docstrings to ignore
_func_call_docstring = types.FunctionType.__call__.__doc__
_object_init_docstring = object.__init__.__doc__
_builtin_type_docstrings = {
immerrr
Use inspect.getdoc when populating _builtin_type_docstrings...
r17025 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
types.FunctionType, property)
MinRK
detect builtin docstrings in oinspect...
r14835 }
Thomas Kluyver
Don't introspect __call__ for simple callables...
r15362
_builtin_func_type = type(all)
_builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
Ville M. Vainio
crlf -> lf
r1032 #****************************************************************************
# Builtin color schemes
Colors = TermColors # just a shorthand
Matthias Bussonnier
Deduplicate code
r21774 InspectColors = PyColorize.ANSICodeColors
Ville M. Vainio
crlf -> lf
r1032
#****************************************************************************
Fernando Perez
Implement object info protocol....
r2931 # Auxiliary functions and objects
# See the messaging spec for the definition of all these fields. This list
# effectively defines the order of display
info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
'length', 'file', 'definition', 'docstring', 'source',
'init_definition', 'class_docstring', 'init_docstring',
'call_def', 'call_docstring',
# These won't be printed but will be used to determine how to
# format the object
Matthias Bussonnier
Deprecate some methods the should not be used anymore...
r25244 'ismagic', 'isalias', 'isclass', 'found', 'name'
Fernando Perez
Implement object info protocol....
r2931 ]
Fernando Perez
Add function signature info to calltips....
r3051 def object_info(**kw):
"""Make an object info dict with all fields present."""
Matthias Bussonnier
cast_unicode code simplification....
r25338 infodict = {k:None for k in info_fields}
Fernando Perez
Implement object info protocol....
r2931 infodict.update(kw)
Fernando Perez
Add function signature info to calltips....
r3051 return infodict
Fernando Perez
Implement object info protocol....
r2931
Jörgen Stenarson
Unicode fix for docstrings in pinfo magic...
r8322 def get_encoding(obj):
"""Get encoding for python source file defining obj
Returns None if obj is not defined in a sourcefile.
"""
ofile = find_file(obj)
# run contents of file through pager starting at line where the object
# is defined, as long as the file isn't binary and is actually on the
# filesystem.
if ofile is None:
return None
elif ofile.endswith(('.so', '.dll', '.pyd')):
return None
elif not os.path.isfile(ofile):
return None
else:
# Print only text files, not extension binaries. Note that
# getsourcelines returns lineno with 1-offset and page() uses
# 0-offset, so we must adjust.
Thomas Kluyver
Explicitly close file in get_encoding
r15467 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
encoding, lines = openpy.detect_encoding(buffer.readline)
Jörgen Stenarson
Unicode fix for docstrings in pinfo magic...
r8322 return encoding
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 def getdoc(obj) -> Union[str,None]:
Ville M. Vainio
crlf -> lf
r1032 """Stable wrapper around inspect.getdoc.
This can't crash because of attribute problems.
It also attempts to call a getdoc() method on the given object. This
allows objects which provide their docstrings via non-standard mechanisms
Sylvain Corlay
pinfo magic return mime bundle
r22460 (like Pyro proxies) to still be inspected by ipython's ? system.
"""
Ville M. Vainio
crlf -> lf
r1032 # Allow objects to offer customized documentation via a getdoc method:
try:
Thomas Kluyver
If object has a getdoc() method, override its normal docstring....
r5535 ds = obj.getdoc()
except Exception:
Ville M. Vainio
crlf -> lf
r1032 pass
else:
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 if isinstance(ds, str):
Thomas Kluyver
Unindent custom docstrings of objects.
r5536 return inspect.cleandoc(ds)
Antony Lee
Simplify oinspect.getdoc....
r24004 docstr = inspect.getdoc(obj)
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 return docstr
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Make our fixed-up getargspec a top-level function....
r1413
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 def getsource(obj, oname='') -> Union[str,None]:
Ville M. Vainio
crlf -> lf
r1032 """Wrapper around inspect.getsource.
This can be modified by other projects to provide customized source
extraction.
immerrr
Print sources for property fget/fset/fdel methods...
r17023 Parameters
----------
obj : object
an object whose source code we will attempt to extract
oname : str
(optional) a name under which the object is known
Ville M. Vainio
crlf -> lf
r1032
immerrr
Print sources for property fget/fset/fdel methods...
r17023 Returns
-------
src : unicode or None
Ville M. Vainio
crlf -> lf
r1032
immerrr
Print sources for property fget/fset/fdel methods...
r17023 """
Ville M. Vainio
crlf -> lf
r1032
immerrr
Print sources for property fget/fset/fdel methods...
r17023 if isinstance(obj, property):
sources = []
for attrname in ['fget', 'fset', 'fdel']:
fn = getattr(obj, attrname)
if fn is not None:
encoding = get_encoding(fn)
oname_prefix = ('%s.' % oname) if oname else ''
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 sources.append(''.join(('# ', oname_prefix, attrname)))
immerrr
Print sources for property fget/fset/fdel methods...
r17023 if inspect.isfunction(fn):
sources.append(dedent(getsource(fn)))
else:
# Default str/repr only prints function name,
# pretty.pretty prints module name too.
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 sources.append(
'%s%s = %s\n' % (oname_prefix, attrname, pretty(fn))
)
immerrr
Print sources for property fget/fset/fdel methods...
r17023 if sources:
return '\n'.join(sources)
else:
return None
Ben Edwards
Display source code correctly for decorated functions....
r4266
Ville M. Vainio
crlf -> lf
r1032 else:
immerrr
Print sources for property fget/fset/fdel methods...
r17023 # Get source for non-property objects.
Min RK
handle multiple decorators in oinspect...
r21505 obj = _get_wrapped(obj)
immerrr
Print sources for property fget/fset/fdel methods...
r17023
Fernando Perez
Fix bug reported by Jeremy Jones where %pfile would fail on object...
r1228 try:
src = inspect.getsource(obj)
except TypeError:
immerrr
Print sources for property fget/fset/fdel methods...
r17023 # The object itself provided no meaningful source, try looking for
# its class definition instead.
if hasattr(obj, '__class__'):
try:
src = inspect.getsource(obj.__class__)
except TypeError:
return None
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 return src
Ville M. Vainio
crlf -> lf
r1032
Thomas Kluyver
Don't introspect __call__ for simple callables...
r15362
def is_simple_callable(obj):
"""True if obj is a function ()"""
return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
Matthias Bussonnier
Deprecate some methods the should not be used anymore...
r25244 @undoc
Fernando Perez
Make our fixed-up getargspec a top-level function....
r1413 def getargspec(obj):
Terry Davis
Remove python 2 references from docstrings, where appropriate.
r25450 """Wrapper around :func:`inspect.getfullargspec`
Chris Mentzel
add list of subclasses when using pinfo - etc
r24820
Thomas Kluyver
Fix the display of functions with keyword-only arguments on Python 3.
r15335 In addition to functions and methods, this can also handle objects with a
``__call__`` attribute.
Matthias Bussonnier
Deprecate some methods the should not be used anymore...
r25244
DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
Thomas Kluyver
Fix the display of functions with keyword-only arguments on Python 3.
r15335 """
Matthias Bussonnier
Deprecate some methods the should not be used anymore...
r25244
warnings.warn('`getargspec` function is deprecated as of IPython 7.10'
'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
Thomas Kluyver
Don't introspect __call__ for simple callables...
r15362 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
Thomas Kluyver
Fix the display of functions with keyword-only arguments on Python 3.
r15335 obj = obj.__call__
Srinivas Reddy Thatiparthy
remove PY3 var
r23086 return inspect.getfullargspec(obj)
Fernando Perez
Make our fixed-up getargspec a top-level function....
r1413
Matthias Bussonnier
Deprecate some methods the should not be used anymore...
r25244 @undoc
Fernando Perez
Add function signature info to calltips....
r3051 def format_argspec(argspec):
"""Format argspect, convenience wrapper around inspect's.
This takes a dict instead of ordered arguments and calls
inspect.format_argspec with the arguments in the necessary order.
Matthias Bussonnier
Deprecate some methods the should not be used anymore...
r25244
DEPRECATED: Do not use; will be removed in future versions.
Fernando Perez
Add function signature info to calltips....
r3051 """
Matthias Bussonnier
Deprecate some methods the should not be used anymore...
r25244
warnings.warn('`format_argspec` function is deprecated as of IPython 7.10'
'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
Fernando Perez
Add function signature info to calltips....
r3051 return inspect.formatargspec(argspec['args'], argspec['varargs'],
argspec['varkw'], argspec['defaults'])
Srinivas Reddy Thatiparthy
This commit,...
r23035 @undoc
Fernando Perez
Add function signature info to calltips....
r3051 def call_tip(oinfo, format_call=True):
Srinivas Reddy Thatiparthy
This commit,...
r23035 """DEPRECATED. Extract call tip data from an oinfo dict.
Fernando Perez
Add function signature info to calltips....
r3051 """
Matthias Bussonnier
Finish up Deprecation of `IPython.core.oinspect.py:call_tip`
r23041 warnings.warn('`call_tip` function is deprecated as of IPython 6.0'
Matthias Bussonnier
Typo in warning
r23047 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
Fernando Perez
Add function signature info to calltips....
r3051 # Get call definition
MinRK
use dict.get(key) instead of dict[key] for pure kernel...
r3934 argspec = oinfo.get('argspec')
Fernando Perez
Add function signature info to calltips....
r3051 if argspec is None:
call_line = None
else:
# Callable objects will have 'self' as their first argument, prune
# it out if it's there for clarity (since users do *not* pass an
# extra first argument explicitly).
try:
has_self = argspec['args'][0] == 'self'
except (KeyError, IndexError):
pass
else:
if has_self:
argspec['args'] = argspec['args'][1:]
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Add function signature info to calltips....
r3051 call_line = oinfo['name']+format_argspec(argspec)
# Now get docstring.
# The priority is: call docstring, constructor docstring, main one.
MinRK
use dict.get(key) instead of dict[key] for pure kernel...
r3934 doc = oinfo.get('call_docstring')
Fernando Perez
Add function signature info to calltips....
r3051 if doc is None:
MinRK
use dict.get(key) instead of dict[key] for pure kernel...
r3934 doc = oinfo.get('init_docstring')
Fernando Perez
Add function signature info to calltips....
r3051 if doc is None:
MinRK
use dict.get(key) instead of dict[key] for pure kernel...
r3934 doc = oinfo.get('docstring','')
Fernando Perez
Add function signature info to calltips....
r3051
return call_line, doc
Fernando Perez
Make our fixed-up getargspec a top-level function....
r1413
Min RK
handle multiple decorators in oinspect...
r21505 def _get_wrapped(obj):
Thomas Kluyver
Limit unwrapping __wrapped__ attributes to prevent infinite loops...
r21905 """Get the original object if wrapped in one or more @decorators
Some objects automatically construct similar objects on any unrecognised
attribute access (e.g. unittest.mock.call). To protect against infinite loops,
this will arbitrarily cut off after 100 levels of obj.__wrapped__
attribute access. --TK, Jan 2016
"""
orig_obj = obj
i = 0
Min RK
handle multiple decorators in oinspect...
r21505 while safe_hasattr(obj, '__wrapped__'):
obj = obj.__wrapped__
Thomas Kluyver
Limit unwrapping __wrapped__ attributes to prevent infinite loops...
r21905 i += 1
if i > 100:
# __wrapped__ is probably a lie, so return the thing we started with
return orig_obj
Min RK
handle multiple decorators in oinspect...
r21505 return obj
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 def find_file(obj) -> str:
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 """Find the absolute path to the file where an object was defined.
This is essentially a robust wrapper around `inspect.getabsfile`.
Returns None if no file can be found.
Parameters
----------
obj : any Python object
Returns
-------
fname : str
The absolute path to the file where the object was defined.
"""
Min RK
handle multiple decorators in oinspect...
r21505 obj = _get_wrapped(obj)
Bradley M. Froehle
oinspect.find_file: Additional safety if file cannot be found....
r7520
fname = None
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 try:
fname = inspect.getabsfile(obj)
except TypeError:
# For an instance, the file that matters is where its class was
# declared.
Fernando Perez
Promote __wrapped__ logic to the top as per review.
r7431 if hasattr(obj, '__class__'):
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 try:
fname = inspect.getabsfile(obj.__class__)
except TypeError:
# Can happen for builtins
Bradley M. Froehle
oinspect.find_file: Additional safety if file cannot be found....
r7520 pass
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 except:
Bradley M. Froehle
oinspect.find_file: Additional safety if file cannot be found....
r7520 pass
MinRK
cast unicode in oinspect.find_file
r8546 return cast_unicode(fname)
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290
def find_source_lines(obj):
"""Find the line number in a file where an object was defined.
This is essentially a robust wrapper around `inspect.getsourcelines`.
Returns None if no file can be found.
Parameters
----------
obj : any Python object
Returns
-------
lineno : int
The line number where the object definition starts.
"""
Min RK
handle multiple decorators in oinspect...
r21505 obj = _get_wrapped(obj)
Chris Mentzel
add list of subclasses when using pinfo - etc
r24820
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 try:
try:
lineno = inspect.getsourcelines(obj)[1]
except TypeError:
# For instances, try the class object like getsource() does
Fernando Perez
Promote __wrapped__ logic to the top as per review.
r7431 if hasattr(obj, '__class__'):
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 lineno = inspect.getsourcelines(obj.__class__)[1]
MinRK
ensure linen is defined in find_source_lines
r9020 else:
lineno = None
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 except:
return None
return lineno
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109 class Inspector(Colorable):
Sylvain Corlay
pinfo magic return mime bundle
r22460
Fernando Perez
Add function signature info to calltips....
r3051 def __init__(self, color_table=InspectColors,
code_color_table=PyColorize.ANSICodeColors,
michaelpacer
Fix help (pinfo2) view highlighting
r23425 scheme=None,
Sylvain Corlay
pinfo magic return mime bundle
r22460 str_detail_level=0,
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109 parent=None, config=None):
super(Inspector, self).__init__(parent=parent, config=config)
Ville M. Vainio
crlf -> lf
r1032 self.color_table = color_table
Matthias Bussonnier
Introduce some classes necessary fro Pygments refactor.
r22109 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
Ville M. Vainio
crlf -> lf
r1032 self.format = self.parser.format
self.str_detail_level = str_detail_level
self.set_active_scheme(scheme)
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 def _getdef(self,obj,oname='') -> Union[str,None]:
Bradley M. Froehle
Docs: replace 'definition header' with 'call signature'
r8707 """Return the call signature for any callable object.
Ville M. Vainio
crlf -> lf
r1032
If any exception is generated, None is returned instead and the
exception is suppressed."""
try:
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 return _render_signature(signature(obj), oname)
Ville M. Vainio
crlf -> lf
r1032 except:
return None
Bernardo B. Marques
remove all trailling spaces
r4872
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 def __head(self,h) -> str:
Ville M. Vainio
crlf -> lf
r1032 """Return a header string with proper colors."""
return '%s%s%s' % (self.color_table.active_colors.header,h,
self.color_table.active_colors.normal)
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 def set_active_scheme(self, scheme):
michaelpacer
Fix help (pinfo2) view highlighting
r23425 if scheme is not None:
self.color_table.set_active_scheme(scheme)
self.parser.color_table.set_active_scheme(scheme)
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 def noinfo(self, msg, oname):
Ville M. Vainio
crlf -> lf
r1032 """Generic message when no information is found."""
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('No %s found' % msg, end=' ')
Ville M. Vainio
crlf -> lf
r1032 if oname:
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('for %s' % oname)
Ville M. Vainio
crlf -> lf
r1032 else:
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print()
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 def pdef(self, obj, oname=''):
Bradley M. Froehle
Docs: replace 'definition header' with 'call signature'
r8707 """Print the call signature for any callable object.
Ville M. Vainio
crlf -> lf
r1032
If the object is a class, print the constructor information."""
if not callable(obj):
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('Object is not callable.')
Ville M. Vainio
crlf -> lf
r1032 return
header = ''
if inspect.isclass(obj):
header = self.__head('Class constructor information:\n')
Srinivas Reddy Thatiparthy
remove Python2 specific code
r23087
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 output = self._getdef(obj,oname)
Ville M. Vainio
crlf -> lf
r1032 if output is None:
self.noinfo('definition header',oname)
else:
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 print(header,self.format(output), end=' ')
Ville M. Vainio
crlf -> lf
r1032
Paul Ivanov
fix oinspect module
r22961 # In Python 3, all classes are new-style, so they all have __init__.
@skip_doctest
def pdoc(self, obj, oname='', formatter=None):
"""Print the docstring for any object.
Optional:
-formatter: a function to run the docstring through for specially
formatted docstrings.
Examples
--------
In [1]: class NoInit:
...: pass
In [2]: class NoDoc:
...: def __init__(self):
...: pass
In [3]: %pdoc NoDoc
No documentation found for NoDoc
In [4]: %pdoc NoInit
No documentation found for NoInit
In [5]: obj = NoInit()
In [6]: %pdoc obj
No documentation found for obj
In [5]: obj2 = NoDoc()
In [6]: %pdoc obj2
No documentation found for obj2
"""
head = self.__head # For convenience
lines = []
ds = getdoc(obj)
if formatter:
ds = formatter(ds).get('plain/text', ds)
if ds:
lines.append(head("Class docstring:"))
lines.append(indent(ds))
if inspect.isclass(obj) and hasattr(obj, '__init__'):
init_ds = getdoc(obj.__init__)
if init_ds is not None:
lines.append(head("Init docstring:"))
lines.append(indent(init_ds))
elif hasattr(obj,'__call__'):
call_ds = getdoc(obj.__call__)
if call_ds:
lines.append(head("Call docstring:"))
lines.append(indent(call_ds))
if not lines:
self.noinfo('documentation',oname)
else:
page.page('\n'.join(lines))
immerrr
Print sources for property fget/fset/fdel methods...
r17023 def psource(self, obj, oname=''):
Ville M. Vainio
crlf -> lf
r1032 """Print the source code for an object."""
# Flush the source cache because inspect can return out-of-date source
linecache.checkcache()
try:
immerrr
Print sources for property fget/fset/fdel methods...
r17023 src = getsource(obj, oname=oname)
except Exception:
src = None
if src is None:
self.noinfo('source', oname)
Ville M. Vainio
crlf -> lf
r1032 else:
jstenar
change oinspect.py to be unicode safe
r8312 page.page(self.format(src))
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 def pfile(self, obj, oname=''):
Ville M. Vainio
crlf -> lf
r1032 """Show the whole file where an object was defined."""
Sylvain Corlay
pinfo magic return mime bundle
r22460
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 lineno = find_source_lines(obj)
if lineno is None:
self.noinfo('file', oname)
Fernando Perez
Fix bug reported by Jeremy Jones where %pfile would fail on object...
r1228 return
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 ofile = find_file(obj)
# run contents of file through pager starting at line where the object
# is defined, as long as the file isn't binary and is actually on the
# filesystem.
Thomas Kluyver
Minor cleanup in oinspect.
r3929 if ofile.endswith(('.so', '.dll', '.pyd')):
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('File %r is binary, not printing.' % ofile)
Fernando Perez
Fix bug reported by Jeremy Jones where %pfile would fail on object...
r1228 elif not os.path.isfile(ofile):
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('File %r does not exist, not printing.' % ofile)
Ville M. Vainio
crlf -> lf
r1032 else:
Fernando Perez
Fix bug reported by Jeremy Jones where %pfile would fail on object...
r1228 # Print only text files, not extension binaries. Note that
# getsourcelines returns lineno with 1-offset and page() uses
# 0-offset, so we must adjust.
Jörgen Stenarson
merge functionality in io and openpy relating to encoding...
r8304 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
Bernardo B. Marques
remove all trailling spaces
r4872
Matthias Bussonnier
cast_unicode code simplification....
r25338
def _mime_format(self, text:str, formatter=None) -> dict:
Sylvain Corlay
pinfo magic return mime bundle
r22460 """Return a mime bundle representation of the input text.
Sylvain Corlay
Sphinxify docstrings
r22459
Sylvain Corlay
pinfo magic return mime bundle
r22460 - if `formatter` is None, the returned mime bundle has
a `text/plain` field, with the input text.
a `text/html` field with a `<pre>` tag containing the input text.
- if `formatter` is not None, it must be a callable transforming the
input text into a mime bundle. Default values for `text/plain` and
`text/html` representations are the ones described above.
Note:
Formatters returning strings are supported but this behavior is deprecated.
"""
defaults = {
'text/plain': text,
'text/html': '<pre>' + text + '</pre>'
}
if formatter is None:
return defaults
else:
formatted = formatter(text)
if not isinstance(formatted, dict):
# Handle the deprecated behavior of a formatter returning
# a string instead of a mime bundle.
return {
'text/plain': formatted,
'text/html': '<pre>' + formatted + '</pre>'
}
else:
return dict(defaults, **formatted)
Matthias Bussonnier
'restore formatting'
r22537
def format_mime(self, bundle):
text_plain = bundle['text/plain']
text = ''
heads, bodies = list(zip(*text_plain))
_len = max(len(h) for h in heads)
for head, body in zip(heads, bodies):
Matthias Bussonnier
Reformat newlines in Tooltips....
r22571 body = body.strip('\n')
Matthias Bussonnier
'restore formatting'
r22537 delim = '\n' if '\n' in body else ' '
text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
bundle['text/plain'] = text
return bundle
Sylvain Corlay
pinfo magic return mime bundle
r22460 def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
Matthias Bussonnier
Cleaning of Oinspect....
r23673 """Retrieve an info dict and format it.
Chris Mentzel
add list of subclasses when using pinfo - etc
r24820
Matthias Bussonnier
Cleaning of Oinspect....
r23673 Parameters
==========
obj: any
Object to inspect and return info from
oname: str (default: ''):
Name of the variable pointing to `obj`.
formatter: callable
info:
luzpaz
Misc. typo fixes...
r24084 already computed information
Matthias Bussonnier
Cleaning of Oinspect....
r23673 detail_level: integer
luzpaz
Misc. typo fixes...
r24084 Granularity of detail level, if set to 1, give more information.
Matthias Bussonnier
Cleaning of Oinspect....
r23673 """
Sylvain Corlay
pinfo magic return mime bundle
r22460
info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
Matthias Bussonnier
'restore formatting'
r22537 _mime = {
'text/plain': [],
Sylvain Corlay
pinfo magic return mime bundle
r22460 'text/html': '',
}
Matthias Bussonnier
cast_unicode code simplification....
r25338 def append_field(bundle, title:str, key:str, formatter=None):
Sylvain Corlay
pinfo magic return mime bundle
r22460 field = info[key]
if field is not None:
formatted_field = self._mime_format(field, formatter)
Matthias Bussonnier
'restore formatting'
r22537 bundle['text/plain'].append((title, formatted_field['text/plain']))
Sylvain Corlay
pinfo magic return mime bundle
r22460 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
def code_formatter(text):
return {
'text/plain': self.format(text),
Matthias Bussonnier
rehighlight in html
r22469 'text/html': pylight(text)
Sylvain Corlay
pinfo magic return mime bundle
r22460 }
Thomas Kluyver
Reorder info fields to put most useful first...
r20568
if info['isalias']:
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Repr', 'string_form')
Thomas Kluyver
Reorder info fields to put most useful first...
r20568
elif info['ismagic']:
Sylvain Corlay
pinfo magic return mime bundle
r22460 if detail_level > 0:
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Source', 'source', code_formatter)
Thomas Kluyver
Allow inspection of source code for magics...
r20697 else:
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Docstring', 'docstring', formatter)
append_field(_mime, 'File', 'file')
Thomas Kluyver
Reorder info fields to put most useful first...
r20568
elif info['isclass'] or is_simple_callable(obj):
# Functions, methods, classes
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Signature', 'definition', code_formatter)
append_field(_mime, 'Init signature', 'init_definition', code_formatter)
Antony Lee
In obj??, display the docstring if it is not in the source....
r24118 append_field(_mime, 'Docstring', 'docstring', formatter)
Min RK
include docstring in detail_level=1 if no source is found...
r23021 if detail_level > 0 and info['source']:
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Source', 'source', code_formatter)
Thomas Kluyver
Reorder info fields to put most useful first...
r20568 else:
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
Thomas Kluyver
Reorder info fields to put most useful first...
r20568
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'File', 'file')
append_field(_mime, 'Type', 'type_name')
Chris Mentzel
add list of subclasses when using pinfo - etc
r24820 append_field(_mime, 'Subclasses', 'subclasses')
Thomas Kluyver
Reorder info fields to put most useful first...
r20568
Ville M. Vainio
crlf -> lf
r1032 else:
Thomas Kluyver
Reorder info fields to put most useful first...
r20568 # General Python objects
Bibo Hao
Show (Call) Signature of object first....
r22852 append_field(_mime, 'Signature', 'definition', code_formatter)
append_field(_mime, 'Call signature', 'call_def', code_formatter)
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Type', 'type_name')
append_field(_mime, 'String form', 'string_form')
Thomas Kluyver
Reorder info fields to put most useful first...
r20568
# Namespace
if info['namespace'] != 'Interactive':
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Namespace', 'namespace')
Thomas Kluyver
Reorder info fields to put most useful first...
r20568
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Length', 'length')
Bibo Hao
Show (Call) Signature of object first....
r22852 append_field(_mime, 'File', 'file')
Chris Mentzel
add list of subclasses when using pinfo - etc
r24820
Thomas Kluyver
Reorder info fields to put most useful first...
r20568 # Source or docstring, depending on detail level and whether
# source found.
Ming Zhang
?? shall show docstring if source info is not available
r23609 if detail_level > 0 and info['source']:
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Source', 'source', code_formatter)
Sylvain Corlay
pinfo magic return mime bundle
r22460 else:
Matthias Bussonnier
'restore formatting'
r22537 append_field(_mime, 'Docstring', 'docstring', formatter)
append_field(_mime, 'Class docstring', 'class_docstring', formatter)
append_field(_mime, 'Init docstring', 'init_docstring', formatter)
append_field(_mime, 'Call docstring', 'call_docstring', formatter)
Chris Mentzel
add list of subclasses when using pinfo - etc
r24820
Sylvain Corlay
pinfo magic return mime bundle
r22460
Matthias Bussonnier
'restore formatting'
r22537 return self.format_mime(_mime)
Sylvain Corlay
pinfo magic return mime bundle
r22460
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
MinRK
add object_inspect_text...
r16579 """Show detailed information about an object.
Optional arguments:
- oname: name of the variable pointing to the object.
Ville M. Vainio
crlf -> lf
r1032
Sylvain Corlay
pinfo magic return mime bundle
r22460 - formatter: callable (optional)
A special formatter for docstrings.
The formatter is a callable that takes a string as an input
and returns either a formatted string or a mime type bundle
luzpaz
Misc. typo fixes...
r24084 in the form of a dictionary.
Sylvain Corlay
pinfo magic return mime bundle
r22460
Although the support of custom formatter returning a string
instead of a mime type bundle is deprecated.
MinRK
add object_inspect_text...
r16579
- info: a structure with some information fields which may have been
precomputed already.
- detail_level: if set to 1, more information is given.
"""
Sylvain Corlay
pinfo magic return mime bundle
r22460 info = self._get_info(obj, oname, formatter, info, detail_level)
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 if not enable_html_pager:
del info['text/html']
page.page(info)
Sylvain Corlay
pinfo magic return mime bundle
r22460
Fernando Perez
Implement object info protocol....
r2931 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
Sylvain Corlay
pinfo magic return mime bundle
r22460 """DEPRECATED. Compute a dict with detailed information about an object.
"""
Matthias Bussonnier
Deprecate only if not None passed as formatter.
r22466 if formatter is not None:
Matthias Bussonnier
Reword deprecation warning.
r22468 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
'is deprecated as of IPython 5.0 and will have no effects.',
Sylvain Corlay
Add deprecation warning
r22462 DeprecationWarning, stacklevel=2)
Sylvain Corlay
pinfo magic return mime bundle
r22460 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
Matthias Bussonnier
Cleaning of Oinspect....
r23673 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
Fernando Perez
Implement object info protocol....
r2931 """Compute a dict with detailed information about an object.
Matthias Bussonnier
Cleaning of Oinspect....
r23673 Parameters
==========
obj: any
An object to find information about
oname: str (default: ''):
Name of the variable pointing to `obj`.
info: (default: None)
A struct (dict like with attr access) with some information fields
which may have been precomputed already.
detail_level: int (default:0)
If set to 1, more information is given.
Returns
=======
Matthias Bussonnier
cast_unicode code simplification....
r25338 An object info dict with known fields from `info_fields`. Keys are
strings, values are string or None.
Fernando Perez
Implement object info protocol....
r2931 """
if info is None:
Matthias Bussonnier
Cleaning of Oinspect....
r23673 ismagic = False
isalias = False
Fernando Perez
Implement object info protocol....
r2931 ospace = ''
else:
ismagic = info.ismagic
isalias = info.isalias
ospace = info.namespace
Fernando Perez
Add function signature info to calltips....
r3051
Fernando Perez
Implement object info protocol....
r2931 # Get docstring, special-casing aliases:
if isalias:
if not callable(obj):
try:
ds = "Alias to the system command:\n %s" % obj[1]
except:
ds = "Alias: " + str(obj)
else:
ds = "Alias to " + str(obj)
if obj.__doc__:
ds += "\nDocstring:\n" + obj.__doc__
else:
ds = getdoc(obj)
if ds is None:
ds = '<no docstring>'
Fernando Perez
Add function signature info to calltips....
r3051 # store output in a dict, we initialize it here and fill it as we go
Matthias Bussonnier
Create subclasses field with None for consistency.
r24829 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Implement object info protocol....
r2931 string_max = 200 # max size of strings to show (snipped if longer)
Sylvain Corlay
pinfo magic return mime bundle
r22460 shalf = int((string_max - 5) / 2)
Fernando Perez
Implement object info protocol....
r2931
if ismagic:
Matthias Bussonnier
Cleaning of Oinspect....
r23673 out['type_name'] = 'Magic function'
Fernando Perez
Implement object info protocol....
r2931 elif isalias:
Matthias Bussonnier
Cleaning of Oinspect....
r23673 out['type_name'] = 'System alias'
Fernando Perez
Implement object info protocol....
r2931 else:
Matthias Bussonnier
Cleaning of Oinspect....
r23673 out['type_name'] = type(obj).__name__
Fernando Perez
Implement object info protocol....
r2931
try:
bclass = obj.__class__
out['base_class'] = str(bclass)
Matthias Bussonnier
Cleaning of Oinspect....
r23673 except:
pass
Fernando Perez
Implement object info protocol....
r2931
# String form, but snip if too long in ? form (full in ??)
if detail_level >= self.str_detail_level:
try:
ostr = str(obj)
str_head = 'string_form'
if not detail_level and len(ostr)>string_max:
ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
ostr = ("\n" + " " * len(str_head.expandtabs())).\
Thomas Kluyver
Further removal of string module from core.
r3160 join(q.strip() for q in ostr.split("\n"))
Fernando Perez
Implement object info protocol....
r2931 out[str_head] = ostr
except:
pass
if ospace:
out['namespace'] = ospace
# Length (for strings and lists)
try:
out['length'] = str(len(obj))
Matthias Bussonnier
Cleaning of Oinspect....
r23673 except Exception:
pass
Fernando Perez
Implement object info protocol....
r2931
# Filename where object was defined
binary_file = False
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 fname = find_file(obj)
if fname is None:
Fernando Perez
Implement object info protocol....
r2931 # if anything goes wrong, we don't want to show source, so it's as
# if the file was binary
binary_file = True
Fernando Perez
Fix finding of file info for magics and decorated functions....
r7290 else:
if fname.endswith(('.so', '.dll', '.pyd')):
binary_file = True
elif fname.endswith('<string>'):
fname = 'Dynamically generated function. No source code available.'
Thomas Kluyver
Collapse user home directory to ~ in info filename
r20569 out['file'] = compress_user(fname)
Bernardo B. Marques
remove all trailling spaces
r4872
immerrr
Print sources for property fget/fset/fdel methods...
r17023 # Original source code for a callable, class or property.
Fernando Perez
Implement object info protocol....
r2931 if detail_level:
# Flush the source cache because inspect can return out-of-date
# source
linecache.checkcache()
try:
immerrr
Print sources for property fget/fset/fdel methods...
r17023 if isinstance(obj, property) or not binary_file:
src = getsource(obj, oname)
if src is not None:
src = src.rstrip()
out['source'] = src
Thomas Kluyver
Refactor Inspector.pinfo(), so it no longer duplicates code in Inspector.info()
r3856 except Exception:
Thomas Kluyver
Better check for missing source in Inspector.info()
r3857 pass
Bernardo B. Marques
remove all trailling spaces
r4872
immerrr
Print sources for property fget/fset/fdel methods...
r17023 # Add docstring only if no source is to be shown (avoid repetitions).
Antony Lee
In obj??, display the docstring if it is not in the source....
r24118 if ds and not self._source_contains_docstring(out.get('source'), ds):
immerrr
Print sources for property fget/fset/fdel methods...
r17023 out['docstring'] = ds
Fernando Perez
Implement object info protocol....
r2931
# Constructor docstring for classes
if inspect.isclass(obj):
Thomas Kluyver
Refactor Inspector.pinfo(), so it no longer duplicates code in Inspector.info()
r3856 out['isclass'] = True
Min RK
Get signatures directly from classes...
r22171
Min RK
handle None for init_def
r22176 # get the init signature:
Min RK
Get signatures directly from classes...
r22171 try:
init_def = self._getdef(obj, oname)
except AttributeError:
init_def = None
Min RK
handle None for init_def
r22176
Min RK
Get signatures directly from classes...
r22171 # get the __init__ docstring
Fernando Perez
Implement object info protocol....
r2931 try:
Min RK
Get signatures directly from classes...
r22171 obj_init = obj.__init__
Fernando Perez
Implement object info protocol....
r2931 except AttributeError:
Min RK
handle None for init_def
r22176 init_ds = None
Fernando Perez
Implement object info protocol....
r2931 else:
Min RK
get signature from init if top-level signature fails...
r22539 if init_def is None:
# Get signature from init if top-level sig failed.
# Can happen for built-in types (list, etc.).
try:
init_def = self._getdef(obj_init, oname)
except AttributeError:
pass
Min RK
handle None for init_def
r22176 init_ds = getdoc(obj_init)
Fernando Perez
Implement object info protocol....
r2931 # Skip Python's auto-generated docstrings
MinRK
detect builtin docstrings in oinspect...
r14835 if init_ds == _object_init_docstring:
Fernando Perez
Implement object info protocol....
r2931 init_ds = None
Min RK
get signature from init if top-level signature fails...
r22539 if init_def:
out['init_definition'] = init_def
Min RK
Get signatures directly from classes...
r22171 if init_ds:
out['init_docstring'] = init_ds
Fernando Perez
Add function signature info to calltips....
r3051
Matthias Bussonnier
Handle edge case when requesting subclasses....
r24946 names = [sub.__name__ for sub in type.__subclasses__(obj)]
Matthias Bussonnier
Update what's new and limit number of subclasses....
r24858 if len(names) < 10:
all_names = ', '.join(names)
else:
all_names = ', '.join(names[:10]+['...'])
Chris Mentzel
add list of subclasses when using pinfo - etc
r24820 out['subclasses'] = all_names
Fernando Perez
Implement object info protocol....
r2931 # and class docstring for instances:
Thomas Kluyver
Refactor Inspector.pinfo(), so it no longer duplicates code in Inspector.info()
r3856 else:
MinRK
Update signature presentation in pinfo classes...
r15711 # reconstruct the function definition and print it:
defln = self._getdef(obj, oname)
if defln:
Sylvain Corlay
pinfo magic return mime bundle
r22460 out['definition'] = defln
MinRK
Update signature presentation in pinfo classes...
r15711
Fernando Perez
Implement object info protocol....
r2931 # First, check whether the instance docstring is identical to the
# class one, and print it separately if they don't coincide. In
# most cases they will, but it's nice to print all the info for
# objects which use instance-customized docstrings.
if ds:
try:
cls = getattr(obj,'__class__')
except:
class_ds = None
else:
class_ds = getdoc(cls)
# Skip Python's auto-generated docstrings
MinRK
detect builtin docstrings in oinspect...
r14835 if class_ds in _builtin_type_docstrings:
Fernando Perez
Implement object info protocol....
r2931 class_ds = None
if class_ds and ds != class_ds:
Fernando Perez
Add function signature info to calltips....
r3051 out['class_docstring'] = class_ds
Fernando Perez
Implement object info protocol....
r2931
# Next, try to show constructor docstrings
try:
init_ds = getdoc(obj.__init__)
# Skip Python's auto-generated docstrings
MinRK
detect builtin docstrings in oinspect...
r14835 if init_ds == _object_init_docstring:
Fernando Perez
Implement object info protocol....
r2931 init_ds = None
except AttributeError:
init_ds = None
if init_ds:
Fernando Perez
Add function signature info to calltips....
r3051 out['init_docstring'] = init_ds
Fernando Perez
Implement object info protocol....
r2931
# Call form docstring for callable instances
Thomas Kluyver
Don't introspect __call__ for simple callables...
r15362 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
Fernando Perez
Add function signature info to calltips....
r3051 call_def = self._getdef(obj.__call__, oname)
Matthias Bussonnier
'Simplify affectation'
r22465 if call_def and (call_def != out.get('definition')):
MinRK
Update signature presentation in pinfo classes...
r15711 # it may never be the case that call def and definition differ,
# but don't include the same signature twice
Matthias Bussonnier
'Simplify affectation'
r22465 out['call_def'] = call_def
Fernando Perez
Implement object info protocol....
r2931 call_ds = getdoc(obj.__call__)
# Skip Python's auto-generated docstrings
MinRK
detect builtin docstrings in oinspect...
r14835 if call_ds == _func_call_docstring:
Fernando Perez
Implement object info protocol....
r2931 call_ds = None
if call_ds:
Fernando Perez
Add function signature info to calltips....
r3051 out['call_docstring'] = call_ds
return object_info(**out)
Fernando Perez
Implement object info protocol....
r2931
Antony Lee
In obj??, display the docstring if it is not in the source....
r24118 @staticmethod
def _source_contains_docstring(src, doc):
"""
Check whether the source *src* contains the docstring *doc*.
This is is helper function to skip displaying the docstring if the
source already contains it, avoiding repetition of information.
"""
try:
def_node, = ast.parse(dedent(src)).body
return ast.get_docstring(def_node) == doc
except Exception:
# The source can become invalid or even non-existent (because it
# is re-fetched from the source file) so the above code fail in
# arbitrary ways.
return False
Ville M. Vainio
crlf -> lf
r1032 def psearch(self,pattern,ns_table,ns_search=[],
Matthias Bussonnier
made list_types kwarg only.
r25004 ignore_case=False,show_all=False, *, list_types=False):
Ville M. Vainio
crlf -> lf
r1032 """Search namespaces with wildcards for objects.
Arguments:
- pattern: string containing shell-like wildcards to use in namespace
Thomas Kluyver
Improvements to docs formatting.
r12553 searches and optionally a type specification to narrow the search to
objects of that type.
Ville M. Vainio
crlf -> lf
r1032
- ns_table: dict of name->namespaces for search.
Optional arguments:
Bernardo B. Marques
remove all trailling spaces
r4872
Ville M. Vainio
crlf -> lf
r1032 - ns_search: list of namespace names to include in search.
- ignore_case(False): make the search case-insensitive.
- show_all(False): show all names, including those starting with
Thomas Kluyver
Improvements to docs formatting.
r12553 underscores.
Andreas
Added support to list available object types, to use on object type matching in magic function %psearch.
r24996
- list_types(False): list all available object types for object matching.
Ville M. Vainio
crlf -> lf
r1032 """
#print 'ps pattern:<%r>' % pattern # dbg
Bernardo B. Marques
remove all trailling spaces
r4872
Ville M. Vainio
crlf -> lf
r1032 # defaults
type_pattern = 'all'
filter = ''
Andreas
Added support to list available object types, to use on object type matching in magic function %psearch.
r24996 # list all object types
if list_types:
page.page('\n'.join(sorted(typestr2type)))
return
Ville M. Vainio
crlf -> lf
r1032 cmds = pattern.split()
len_cmds = len(cmds)
if len_cmds == 1:
# Only filter pattern given
filter = cmds[0]
elif len_cmds == 2:
# Both filter and type specified
filter,type_pattern = cmds
else:
raise ValueError('invalid argument string for psearch: <%s>' %
pattern)
# filter search namespaces
for name in ns_search:
if name not in ns_table:
raise ValueError('invalid namespace <%s>. Valid names: %s' %
(name,ns_table.keys()))
#print 'type_pattern:',type_pattern # dbg
Thomas Kluyver
Fix wildcard search for new namespace model....
r5550 search_result, namespaces_seen = set(), set()
Ville M. Vainio
crlf -> lf
r1032 for ns_name in ns_search:
ns = ns_table[ns_name]
Thomas Kluyver
Fix wildcard search for new namespace model....
r5550 # Normally, locals and globals are the same, so we just check one.
if id(ns) in namespaces_seen:
continue
namespaces_seen.add(id(ns))
tmp_res = list_namespace(ns, type_pattern, filter,
ignore_case=ignore_case, show_all=show_all)
search_result.update(tmp_res)
page.page('\n'.join(sorted(search_result)))
Philipp A
Render signatures ourselves if they’re too long...
r24841
Matthias Bussonnier
Remove some of the cast_unicode as we can prove they are not bytes....
r25333 def _render_signature(obj_signature, obj_name) -> str:
Philipp A
No need for self here
r24847 """
This was mostly taken from inspect.Signature.__str__.
Look there for the comments.
The only change is to add linebreaks when this gets too long.
"""
result = []
pos_only = False
kw_only = True
for param in obj_signature.parameters.values():
Philipp A
Use names from module
r24848 if param.kind == inspect._POSITIONAL_ONLY:
Philipp A
No need for self here
r24847 pos_only = True
elif pos_only:
Philipp A
Render signatures ourselves if they’re too long...
r24841 result.append('/')
Philipp A
No need for self here
r24847 pos_only = False
Philipp A
Render signatures ourselves if they’re too long...
r24841
Philipp A
Use names from module
r24848 if param.kind == inspect._VAR_POSITIONAL:
Philipp A
No need for self here
r24847 kw_only = False
Philipp A
Use names from module
r24848 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
Philipp A
No need for self here
r24847 result.append('*')
kw_only = False
result.append(str(param))
if pos_only:
result.append('/')
# add up name, parameters, braces (2), and commas
if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
# This doesn’t fit behind “Signature: ” in an inspect window.
Philipp A
Fix signature rendering
r24881 rendered = '{}(\n{})'.format(obj_name, ''.join(
' {},\n'.format(r) for r in result)
)
Philipp A
No need for self here
r24847 else:
rendered = '{}({})'.format(obj_name, ', '.join(result))
Philipp A
Render signatures ourselves if they’re too long...
r24841
Philipp A
Use names from module
r24848 if obj_signature.return_annotation is not inspect._empty:
anno = inspect.formatannotation(obj_signature.return_annotation)
Philipp A
No need for self here
r24847 rendered += ' -> {}'.format(anno)
Philipp A
Render signatures ourselves if they’re too long...
r24841
Philipp A
No need for self here
r24847 return rendered