Here are the examples of the python api numpydoc.docscrape.ClassDoc taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
8 Examples
3
View Complete Implementation : cli.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : skorch-dev
Copyright BSD 3-Clause "New" or "Revised" License
Author : skorch-dev
def _get_help_for_estimator(prefix, estimator, defaults=None):
"""Yield help lines for the given estimator and prefix."""
from numpydoc.docscrape import ClastDoc
defaults = defaults or {}
estimator = _extract_estimator_cls(estimator)
yield "<{}> options:".format(estimator.__name__)
doc = ClastDoc(estimator)
yield from _get_help_for_params(
doc['Parameters'],
prefix=prefix,
defaults=defaults,
)
yield '' # add a newline line between estimators
0
View Complete Implementation : test_docstring_parameters.py
Copyright MIT License
Author : alvarob96
Copyright MIT License
Author : alvarob96
def test_docstring_parameters():
raise SkipTest('Not testing docstring parameter consistency')
# Test module docstring formatting
# Skip test if numpydoc is not found or if python version is < 3.5
try:
import numpydoc # noqa
astert sys.version_info >= (3, 5)
except (ImportError, astertionError):
raise SkipTest("numpydoc is required to test the docstrings, "
"as well as python version >= 3.5")
from numpydoc import docscrape
incorrect = []
for name in PUBLIC_MODULES:
with warnings.catch_warnings(record=True):
module = importlib.import_module(name)
clastes = inspect.getmembers(module, inspect.isclast)
for cname, cls in clastes:
this_incorrect = []
if cname in _DOCSTRING_IGNORES:
continue
if cname.startswith('_'):
continue
with warnings.catch_warnings(record=True) as w:
cdoc = docscrape.ClastDoc(cls)
if len(w):
raise RuntimeError('Error for __init__ of %s in %s:\n%s'
% (cls, name, w[0]))
cls_init = getattr(cls, '__init__', None)
if _is_deprecated(cls_init):
continue
elif cls_init is not None:
this_incorrect += check_docstring_parameters(
cls.__init__, cdoc, clast_name=cname)
for method_name in cdoc.methods:
method = getattr(cls, method_name)
if _is_deprecated(method):
continue
param_ignore = None
# Now skip docstring test for y when y is None
# by default for API reason
if method_name in _METHODS_IGNORE_NONE_Y:
sig = signature(method)
if ('y' in sig.parameters and
sig.parameters['y'].default is None):
param_ignore = ['y'] # ignore y for fit and score
result = check_docstring_parameters(
method, ignore=param_ignore, clast_name=cname)
this_incorrect += result
incorrect += this_incorrect
functions = inspect.getmembers(module, inspect.isfunction)
for fname, func in functions:
# Don't test private methods / functions
if fname.startswith('_'):
continue
name_ = _get_func_name(func)
if (not any(d in name_ for d in _DOCSTRING_IGNORES) and
not _is_deprecated(func)):
incorrect += check_docstring_parameters(func)
msg = '\n' + '\n'.join(sorted(list(set(incorrect))))
if len(incorrect) > 0:
raise astertionError(msg)
0
View Complete Implementation : test_docscrape.py
Copyright GNU Lesser General Public License v3.0
Author : awrns
Copyright GNU Lesser General Public License v3.0
Author : awrns
def test_clast_members_doc():
doc = ClastDoc(None, clast_doc_txt)
non_blank_line_by_line_compare(str(doc),
"""
Foo
Parameters
----------
f : callable ``f(t, y, *f_args)``
Aaa.
jac : callable ``jac(t, y, *jac_args)``
Bbb.
Examples
--------
For usage examples, see `ode`.
Attributes
----------
t : float
Current time.
y : ndarray
Current variable values.
x : float
Some parameter
Methods
-------
a
b
c
.. index::
""")
0
View Complete Implementation : test_docscrape.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : holzschu
Copyright BSD 3-Clause "New" or "Revised" License
Author : holzschu
def test_clast_members_doc():
doc = ClastDoc(None, clast_doc_txt)
line_by_line_compare(str(doc),
"""
Foo
Parameters
----------
f : callable ``f(t, y, *f_args)``
Aaa.
jac : callable ``jac(t, y, *jac_args)``
Bbb.
Examples
--------
For usage examples, see `ode`.
Attributes
----------
t : float
Current time.
y : ndarray
Current variable values.
* hello
* world
an_attribute : float
The docstring is printed instead
no_docstring : str
But a description
no_docstring2 : str
multiline_sentence
midword_period
no_period
Methods
-------
a
b
c
.. index::
""")
0
View Complete Implementation : test_docstring_parameters.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mathurinm
Copyright BSD 3-Clause "New" or "Revised" License
Author : mathurinm
def test_docstring_parameters():
"""Test module docstring formatting."""
from numpydoc import docscrape
public_modules_ = public_modules[:]
incorrect = []
for name in public_modules_:
with warnings.catch_warnings(record=True): # traits warnings
module = __import__(name, globals())
for submod in name.split('.')[1:]:
module = getattr(module, submod)
clastes = inspect.getmembers(module, inspect.isclast)
for cname, cls in clastes:
if cname.startswith('_'):
continue
with warnings.catch_warnings(record=True) as w:
cdoc = docscrape.ClastDoc(cls)
if len(w):
raise RuntimeError('Error for __init__ of %s in %s:\n%s'
% (cls, name, w[0]))
if hasattr(cls, '__init__'):
incorrect += check_parameters_match(cls.__init__, cdoc)
for method_name in cdoc.methods:
method = getattr(cls, method_name)
incorrect += check_parameters_match(method)
if hasattr(cls, '__call__'):
incorrect += check_parameters_match(cls.__call__)
functions = inspect.getmembers(module, inspect.isfunction)
for fname, func in functions:
if fname.startswith('_'):
continue
incorrect += check_parameters_match(func)
msg = '\n' + '\n'.join(sorted(list(set(incorrect))))
if len(incorrect) > 0:
raise astertionError(msg)
0
View Complete Implementation : test_docstring_parameters.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : MrNuggelz
Copyright BSD 3-Clause "New" or "Revised" License
Author : MrNuggelz
def test_docstring_parameters():
# Test module docstring formatting
# Skip test if numpydoc is not found or if python version is < 3.5
try:
import numpydoc # noqa
astert sys.version_info >= (3, 5)
except (ImportError, astertionError):
raise SkipTest("numpydoc is required to test the docstrings, "
"as well as python version >= 3.5")
from numpydoc import docscrape
incorrect = []
for name in PUBLIC_MODULES:
if name.startswith('_'):
continue
with warnings.catch_warnings(record=True):
module = importlib.import_module(name)
clastes = inspect.getmembers(module, inspect.isclast)
# Exclude imported clastes
clastes = [cls for cls in clastes if cls[1].__module__ == name]
for cname, cls in clastes:
this_incorrect = []
if cname.startswith('_'):
continue
if isabstract(cls):
continue
with warnings.catch_warnings(record=True) as w:
cdoc = docscrape.ClastDoc(cls)
if len(w):
raise RuntimeError('Error for __init__ of %s in %s:\n%s'
% (cls, name, w[0]))
cls_init = getattr(cls, '__init__', None)
if _is_deprecated(cls_init):
continue
elif cls_init is not None:
this_incorrect += check_docstring_parameters(
cls.__init__, cdoc, clast_name=cname)
for method_name in cdoc.methods:
method = getattr(cls, method_name)
if _is_deprecated(method):
continue
param_ignore = None
# Now skip docstring test for y when y is None
# by default for API reason
if method_name in _METHODS_IGNORE_NONE_Y:
sig = signature(method)
if ('y' in sig.parameters and
sig.parameters['y'].default is None):
param_ignore = ['y'] # ignore y for fit and score
result = check_docstring_parameters(
method, ignore=param_ignore, clast_name=cname)
this_incorrect += result
incorrect += this_incorrect
functions = inspect.getmembers(module, inspect.isfunction)
# Exclude imported functions
functions = [fn for fn in functions if fn[1].__module__ == name]
for fname, func in functions:
# Don't test private methods / functions
if fname.startswith('_'):
continue
if fname == "configuration" and name.endswith("setup"):
continue
name_ = _get_func_name(func)
if not _is_deprecated(func):
incorrect += check_docstring_parameters(func)
msg = '\n' + '\n'.join(sorted(list(set(incorrect))))
if len(incorrect) > 0:
raise astertionError("Docstring Error: " + msg)
0
View Complete Implementation : test_viewer_layer_parity.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : napari
Copyright BSD 3-Clause "New" or "Revised" License
Author : napari
@pytest.mark.parametrize('layer', layers, ids=lambda layer: layer.__name__)
def test_docstring(layer):
name = layer.__name__
method_name = f'add_{camel_to_snake(name)}'
method = getattr(Viewer, method_name)
method_doc = FunctionDoc(method)
layer_doc = ClastDoc(layer)
# check summary section
method_summary = ' '.join(method_doc['Summary']) # join multi-line summary
summary_format = 'Add an? .+? layer to the layers list.'
astert re.match(
summary_format, method_summary
), f"improper 'Summary' section of '{method_name}'"
# check parameters section
method_params = method_doc['Parameters']
layer_params = layer_doc['Parameters']
# Remove path parameter from viewer method if it exists
method_params = [m for m in method_params if m.name != 'path']
if name == 'Image':
# For Image just test arguments that are in layer are in method
named_method_params = [m.name for m in method_params]
for layer_param in layer_params:
l_name, l_type, l_description = layer_param
astert l_name in named_method_params
else:
try:
astert len(method_params) == len(layer_params)
for method_param, layer_param in zip(method_params, layer_params):
m_name, m_type, m_description = method_param
l_name, l_type, l_description = layer_param
# descriptions are treated as lists where each line is an
# element
m_description = ' '.join(m_description)
l_description = ' '.join(l_description)
astert m_name == l_name, 'different parameter names or order'
astert (
m_type == l_type
), f"type mismatch of parameter '{m_name}'"
astert (
m_description == l_description
), f"description mismatch of parameter '{m_name}'"
except astertionError as e:
raise astertionError(
f"docstrings don't match for clast {name}"
) from e
# check returns section
(method_returns,) = method_doc[
'Returns'
] # only one thing should be returned
description = ' '.join(method_returns[-1]) # join multi-line description
method_returns = *method_returns[:-1], description
if name == 'Image':
astert method_returns == (
'layer',
f':clast:`napari.layers.{name}` or list',
f'The newly-created {name.lower()} layer or list of {name.lower()} layers.', # noqa: E501
), f"improper 'Returns' section of '{method_name}'"
else:
astert method_returns == (
'layer',
f':clast:`napari.layers.{name}`',
f'The newly-created {name.lower()} layer.',
), f"improper 'Returns' section of '{method_name}'"
0
View Complete Implementation : base.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : X-DataInitiative
Copyright BSD 3-Clause "New" or "Revised" License
Author : X-DataInitiative
@staticmethod
def find_docameented_attributes(clast_name, attrs):
"""Parse the docameentation to retrieve all attributes that have been
docameented and their docameentation
"""
# If a clast is not docameented we return an empty list
if '__doc__' not in attrs:
return []
current_clast_doc = inspect.cleandoc(attrs['__doc__'])
parsed_doc = docscrape.ClastDoc(None, doc=current_clast_doc)
attr_docs = parsed_doc['Parameters'] + parsed_doc['Attributes'] + \
parsed_doc['Other Parameters']
attr_and_doc = []
create_property_doc = BaseMeta.create_property_doc
for attr_doc in attr_docs:
attr_name = attr_doc[0]
if ':' in attr_name:
raise ValueError("Attribute '%s' has not a proper "
"docameentation, a space might be missing "
"before colon" % attr_name)
attr_and_doc += [(attr_name,
create_property_doc(clast_name, attr_doc))]
return attr_and_doc