[Python-modules-commits] [numpydoc] 02/08: Import numpydoc_0.6.0+ds1.orig.tar.gz

Ghislain Vaillant ghisvail-guest at moszumanska.debian.org
Fri Dec 23 16:03:43 UTC 2016


This is an automated email from the git hooks/post-receive script.

ghisvail-guest pushed a commit to branch master
in repository numpydoc.

commit 3195aad0cb15be9f3cae62fb65ff12ac65833634
Author: Ghislain Antony Vaillant <ghisvail at gmail.com>
Date:   Fri Dec 23 15:32:50 2016 +0000

    Import numpydoc_0.6.0+ds1.orig.tar.gz
---
 MANIFEST.in                            |   6 ++
 PKG-INFO                               |  12 ++-
 README.rst                             |   8 ++
 numpydoc.egg-info/PKG-INFO             |  16 ----
 numpydoc.egg-info/SOURCES.txt          |  23 -----
 numpydoc.egg-info/dependency_links.txt |   1 -
 numpydoc.egg-info/top_level.txt        |   1 -
 numpydoc/docscrape.py                  | 160 ++++++++++++++++++++++-----------
 numpydoc/docscrape_sphinx.py           |  32 ++++---
 numpydoc/linkcode.py                   |  83 -----------------
 numpydoc/numpydoc.py                   |  57 ++++++++----
 numpydoc/tests/test_docscrape.py       | 148 +++++++++++++++++++++++++++++-
 numpydoc/tests/test_linkcode.py        |   5 --
 numpydoc/traitsdoc.py                  |   3 +-
 setup.cfg                              |   5 --
 setup.py                               |  17 +++-
 16 files changed, 353 insertions(+), 224 deletions(-)

diff --git a/MANIFEST.in b/MANIFEST.in
index 5176d48..fc18eaf 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,2 +1,8 @@
+include MANIFEST.in
 recursive-include numpydoc/tests *.py
 include *.txt
+include *.rst
+
+# Exclude what we don't want to include
+prune */__pycache__
+global-exclude *.pyc *~ *.bak *.swp *.pyo
diff --git a/PKG-INFO b/PKG-INFO
index c363407..6d1717e 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
 Metadata-Version: 1.1
 Name: numpydoc
-Version: 0.5
+Version: 0.6.0
 Summary: Sphinx extension to support docstrings in Numpy format
 Home-page: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
 Author: Pauli Virtanen and others
@@ -9,8 +9,16 @@ License: BSD
 Description: UNKNOWN
 Keywords: sphinx numpy
 Platform: UNKNOWN
-Classifier: Development Status :: 3 - Alpha
+Classifier: Development Status :: 4 - Beta
 Classifier: Environment :: Plugins
 Classifier: License :: OSI Approved :: BSD License
 Classifier: Topic :: Documentation
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
 Requires: sphinx (>= 1.0.1)
diff --git a/README.rst b/README.rst
index e2711e1..7c93abc 100644
--- a/README.rst
+++ b/README.rst
@@ -45,12 +45,20 @@ The following options can be set in conf.py:
 
   Whether to show all members of a class in the Methods and Attributes
   sections automatically.
+  ``True`` by default.
+
+- numpydoc_show_inherited_class_members: bool
+
+  Whether to show all inherited members of a class in the Methods and Attributes
+  sections automatically. If it's false, inherited members won't shown.
+  ``True`` by default.
 
 - numpydoc_class_members_toctree: bool
 
   Whether to create a Sphinx table of contents for the lists of class
   methods and attributes. If a table of contents is made, Sphinx expects
   each entry to have a separate page.
+  ``True`` by default.
 
 - numpydoc_edit_link: bool  (DEPRECATED -- edit your HTML template instead)
 
diff --git a/numpydoc.egg-info/PKG-INFO b/numpydoc.egg-info/PKG-INFO
deleted file mode 100644
index c363407..0000000
--- a/numpydoc.egg-info/PKG-INFO
+++ /dev/null
@@ -1,16 +0,0 @@
-Metadata-Version: 1.1
-Name: numpydoc
-Version: 0.5
-Summary: Sphinx extension to support docstrings in Numpy format
-Home-page: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
-Author: Pauli Virtanen and others
-Author-email: pav at iki.fi
-License: BSD
-Description: UNKNOWN
-Keywords: sphinx numpy
-Platform: UNKNOWN
-Classifier: Development Status :: 3 - Alpha
-Classifier: Environment :: Plugins
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Topic :: Documentation
-Requires: sphinx (>= 1.0.1)
diff --git a/numpydoc.egg-info/SOURCES.txt b/numpydoc.egg-info/SOURCES.txt
deleted file mode 100644
index b6246c0..0000000
--- a/numpydoc.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-LICENSE.txt
-MANIFEST.in
-README.rst
-setup.py
-numpydoc/__init__.py
-numpydoc/comment_eater.py
-numpydoc/compiler_unparse.py
-numpydoc/docscrape.py
-numpydoc/docscrape_sphinx.py
-numpydoc/linkcode.py
-numpydoc/numpydoc.py
-numpydoc/phantom_import.py
-numpydoc/plot_directive.py
-numpydoc/traitsdoc.py
-numpydoc.egg-info/PKG-INFO
-numpydoc.egg-info/SOURCES.txt
-numpydoc.egg-info/dependency_links.txt
-numpydoc.egg-info/top_level.txt
-numpydoc/tests/test_docscrape.py
-numpydoc/tests/test_linkcode.py
-numpydoc/tests/test_phantom_import.py
-numpydoc/tests/test_plot_directive.py
-numpydoc/tests/test_traitsdoc.py
\ No newline at end of file
diff --git a/numpydoc.egg-info/dependency_links.txt b/numpydoc.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/numpydoc.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/numpydoc.egg-info/top_level.txt b/numpydoc.egg-info/top_level.txt
deleted file mode 100644
index a2954e3..0000000
--- a/numpydoc.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-numpydoc
diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py
index 2b1719d..ed1760b 100644
--- a/numpydoc/docscrape.py
+++ b/numpydoc/docscrape.py
@@ -24,10 +24,10 @@ class Reader(object):
            String with lines separated by '\n'.
 
         """
-        if isinstance(data,list):
+        if isinstance(data, list):
             self._str = data
         else:
-            self._str = data.split('\n') # store string as list of lines
+            self._str = data.split('\n')  # store string as list of lines
 
         self.reset()
 
@@ -35,7 +35,7 @@ class Reader(object):
         return self._str[n]
 
     def reset(self):
-        self._l = 0 # current line nr
+        self._l = 0  # current line nr
 
     def read(self):
         if not self.eof():
@@ -67,8 +67,10 @@ class Reader(object):
 
     def read_to_next_empty_line(self):
         self.seek_next_non_empty_line()
+
         def is_empty(line):
             return not line.strip()
+
         return self.read_to_condition(is_empty)
 
     def read_to_next_unindented_line(self):
@@ -76,7 +78,7 @@ class Reader(object):
             return (line.strip() and (len(line.lstrip()) == len(line)))
         return self.read_to_condition(is_unindented)
 
-    def peek(self,n=0):
+    def peek(self, n=0):
         if self._l + n < len(self._str):
             return self[self._l + n]
         else:
@@ -86,8 +88,17 @@ class Reader(object):
         return not ''.join(self._str).strip()
 
 
-class NumpyDocString(object):
+class ParseError(Exception):
+    def __str__(self):
+        message = self.message
+        if hasattr(self, 'docstring'):
+            message = "%s in %r" % (message, self.docstring)
+        return message
+
+
+class NumpyDocString(collections.Mapping):
     def __init__(self, docstring, config={}):
+        orig_docstring = docstring
         docstring = textwrap.dedent(docstring).split('\n')
 
         self._doc = Reader(docstring)
@@ -97,6 +108,7 @@ class NumpyDocString(object):
             'Extended Summary': [],
             'Parameters': [],
             'Returns': [],
+            'Yields': [],
             'Raises': [],
             'Warns': [],
             'Other Parameters': [],
@@ -110,17 +122,27 @@ class NumpyDocString(object):
             'index': {}
             }
 
-        self._parse()
+        try:
+            self._parse()
+        except ParseError as e:
+            e.docstring = orig_docstring
+            raise
 
-    def __getitem__(self,key):
+    def __getitem__(self, key):
         return self._parsed_data[key]
 
-    def __setitem__(self,key,val):
+    def __setitem__(self, key, val):
         if key not in self._parsed_data:
             warn("Unknown section %s" % key)
         else:
             self._parsed_data[key] = val
 
+    def __iter__(self):
+        return iter(self._parsed_data)
+
+    def __len__(self):
+        return len(self._parsed_data)
+
     def _is_at_section(self):
         self._doc.seek_next_non_empty_line()
 
@@ -132,17 +154,19 @@ class NumpyDocString(object):
         if l1.startswith('.. index::'):
             return True
 
-        l2 = self._doc.peek(1).strip() #    ---------- or ==========
+        l2 = self._doc.peek(1).strip()  # ---------- or ==========
         return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1))
 
-    def _strip(self,doc):
+    def _strip(self, doc):
         i = 0
         j = 0
-        for i,line in enumerate(doc):
-            if line.strip(): break
+        for i, line in enumerate(doc):
+            if line.strip():
+                break
 
-        for j,line in enumerate(doc[::-1]):
-            if line.strip(): break
+        for j, line in enumerate(doc[::-1]):
+            if line.strip():
+                break
 
         return doc[i:len(doc)-j]
 
@@ -150,7 +174,7 @@ class NumpyDocString(object):
         section = self._doc.read_to_next_empty_line()
 
         while not self._is_at_section() and not self._doc.eof():
-            if not self._doc.peek(-1).strip(): # previous line was empty
+            if not self._doc.peek(-1).strip():  # previous line was empty
                 section += ['']
 
             section += self._doc.read_to_next_empty_line()
@@ -162,14 +186,14 @@ class NumpyDocString(object):
             data = self._read_to_next_section()
             name = data[0].strip()
 
-            if name.startswith('..'): # index section
+            if name.startswith('..'):  # index section
                 yield name, data[1:]
             elif len(data) < 2:
                 yield StopIteration
             else:
                 yield name, self._strip(data[2:])
 
-    def _parse_param_list(self,content):
+    def _parse_param_list(self, content):
         r = Reader(content)
         params = []
         while not r.eof():
@@ -182,13 +206,13 @@ class NumpyDocString(object):
             desc = r.read_to_next_unindented_line()
             desc = dedent_lines(desc)
 
-            params.append((arg_name,arg_type,desc))
+            params.append((arg_name, arg_type, desc))
 
         return params
 
-
     _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|"
                            r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X)
+
     def _parse_see_also(self, content):
         """
         func_name : Descriptive text
@@ -208,7 +232,7 @@ class NumpyDocString(object):
                     return g[3], None
                 else:
                     return g[2], g[1]
-            raise ValueError("%s is not a item name" % text)
+            raise ParseError("%s is not a item name" % text)
 
         def push_item(name, rest):
             if not name:
@@ -221,7 +245,8 @@ class NumpyDocString(object):
         rest = []
 
         for line in content:
-            if not line.strip(): continue
+            if not line.strip():
+                continue
 
             m = self._name_rgx.match(line)
             if m and line[m.end():].strip().startswith(':'):
@@ -288,11 +313,23 @@ class NumpyDocString(object):
         self._doc.reset()
         self._parse_summary()
 
-        for (section,content) in self._read_sections():
+        sections = list(self._read_sections())
+        section_names = set([section for section, content in sections])
+
+        has_returns = 'Returns' in section_names
+        has_yields = 'Yields' in section_names
+        # We could do more tests, but we are not. Arbitrarily.
+        if has_returns and has_yields:
+            msg = 'Docstring contains both a Returns and Yields section.'
+            raise ValueError(msg)
+
+        for (section, content) in sections:
             if not section.startswith('..'):
-                section = ' '.join([s.capitalize() for s in section.split(' ')])
-            if section in ('Parameters', 'Returns', 'Raises', 'Warns',
-                           'Other Parameters', 'Attributes', 'Methods'):
+                section = (s.capitalize() for s in section.split(' '))
+                section = ' '.join(section)
+            if section in ('Parameters', 'Returns', 'Yields', 'Raises',
+                           'Warns', 'Other Parameters', 'Attributes',
+                           'Methods'):
                 self[section] = self._parse_param_list(content)
             elif section.startswith('.. index::'):
                 self['index'] = self._parse_index(section, content)
@@ -314,7 +351,7 @@ class NumpyDocString(object):
 
     def _str_signature(self):
         if self['Signature']:
-            return [self['Signature'].replace('*','\*')] + ['']
+            return [self['Signature'].replace('*', '\*')] + ['']
         else:
             return ['']
 
@@ -334,7 +371,7 @@ class NumpyDocString(object):
         out = []
         if self[name]:
             out += self._str_header(name)
-            for param,param_type,desc in self[name]:
+            for param, param_type, desc in self[name]:
                 if param_type:
                     out += ['%s : %s' % (param, param_type)]
                 else:
@@ -352,7 +389,8 @@ class NumpyDocString(object):
         return out
 
     def _str_see_also(self, func_role):
-        if not self['See Also']: return []
+        if not self['See Also']:
+            return []
         out = []
         out += self._str_header("See Also")
         last_had_desc = True
@@ -379,7 +417,7 @@ class NumpyDocString(object):
     def _str_index(self):
         idx = self['index']
         out = []
-        out += ['.. index:: %s' % idx.get('default','')]
+        out += ['.. index:: %s' % idx.get('default', '')]
         for section, references in idx.items():
             if section == 'default':
                 continue
@@ -391,12 +429,12 @@ class NumpyDocString(object):
         out += self._str_signature()
         out += self._str_summary()
         out += self._str_extended_summary()
-        for param_list in ('Parameters', 'Returns', 'Other Parameters',
-                           'Raises', 'Warns'):
+        for param_list in ('Parameters', 'Returns', 'Yields',
+                           'Other Parameters', 'Raises', 'Warns'):
             out += self._str_param_list(param_list)
         out += self._str_section('Warnings')
         out += self._str_see_also(func_role)
-        for s in ('Notes','References','Examples'):
+        for s in ('Notes', 'References', 'Examples'):
             out += self._str_section(s)
         for param_list in ('Attributes', 'Methods'):
             out += self._str_param_list(param_list)
@@ -404,17 +442,19 @@ class NumpyDocString(object):
         return '\n'.join(out)
 
 
-def indent(str,indent=4):
+def indent(str, indent=4):
     indent_str = ' '*indent
     if str is None:
         return indent_str
     lines = str.split('\n')
     return '\n'.join(indent_str + l for l in lines)
 
+
 def dedent_lines(lines):
     """Deindent a list of lines maximally"""
     return textwrap.dedent("\n".join(lines)).split("\n")
 
+
 def header(text, style='-'):
     return text + '\n' + style*len(text) + '\n'
 
@@ -422,7 +462,7 @@ def header(text, style='-'):
 class FunctionDoc(NumpyDocString):
     def __init__(self, func, role='func', doc=None, config={}):
         self._f = func
-        self._role = role # e.g. "func" or "meth"
+        self._role = role  # e.g. "func" or "meth"
 
         if doc is None:
             if func is None:
@@ -433,15 +473,17 @@ class FunctionDoc(NumpyDocString):
         if not self['Signature'] and func is not None:
             func, func_name = self.get_func()
             try:
-                # try to read signature
-                if sys.version_info[0] >= 3:
-                    argspec = inspect.getfullargspec(func)
-                else:
-                    argspec = inspect.getargspec(func)
-                argspec = inspect.formatargspec(*argspec)
-                argspec = argspec.replace('*','\*')
-                signature = '%s%s' % (func_name, argspec)
-            except TypeError as e:
+                try:
+                    signature = str(inspect.signature(func))
+                except (AttributeError, ValueError):
+                    # try to read signature, backward compat for older Python
+                    if sys.version_info[0] >= 3:
+                        argspec = inspect.getfullargspec(func)
+                    else:
+                        argspec = inspect.getargspec(func)
+                    signature = inspect.formatargspec(*argspec)
+                signature = '%s%s' % (func_name, signature.replace('*', '\*'))
+            except TypeError:
                 signature = '%s()' % func_name
             self['Signature'] = signature
 
@@ -465,7 +507,7 @@ class FunctionDoc(NumpyDocString):
         if self._role:
             if self._role not in roles:
                 print("Warning: invalid role %s" % self._role)
-            out += '.. %s:: %s\n    \n\n' % (roles.get(self._role,''),
+            out += '.. %s:: %s\n    \n\n' % (roles.get(self._role, ''),
                                              func_name)
 
         out += super(FunctionDoc, self).__str__(func_role=self._role)
@@ -482,6 +524,9 @@ class ClassDoc(NumpyDocString):
             raise ValueError("Expected a class or None, but got %r" % cls)
         self._cls = cls
 
+        self.show_inherited_members = config.get(
+                    'show_inherited_class_members', True)
+
         if modulename and not modulename.endswith('.'):
             modulename += '.'
         self._mod = modulename
@@ -505,27 +550,36 @@ class ClassDoc(NumpyDocString):
                 if not self[field]:
                     doc_list = []
                     for name in sorted(items):
-                         try:
+                        try:
                             doc_item = pydoc.getdoc(getattr(self._cls, name))
                             doc_list.append((name, '', splitlines_x(doc_item)))
-                         except AttributeError:
-                            pass # method doesn't exist
+                        except AttributeError:
+                            pass  # method doesn't exist
                     self[field] = doc_list
 
     @property
     def methods(self):
         if self._cls is None:
             return []
-        return [name for name,func in inspect.getmembers(self._cls)
+        return [name for name, func in inspect.getmembers(self._cls)
                 if ((not name.startswith('_')
                      or name in self.extra_public_methods)
-                    and isinstance(func, collections.Callable))]
+                    and isinstance(func, collections.Callable)
+                    and self._is_show_member(name))]
 
     @property
     def properties(self):
         if self._cls is None:
             return []
-        return [name for name,func in inspect.getmembers(self._cls)
-                if not name.startswith('_') and
-                (func is None or isinstance(func, property) or
-                 inspect.isgetsetdescriptor(func))]
+        return [name for name, func in inspect.getmembers(self._cls)
+                if (not name.startswith('_') and
+                    (func is None or isinstance(func, property) or
+                     inspect.isgetsetdescriptor(func))
+                    and self._is_show_member(name))]
+
+    def _is_show_member(self, name):
+        if self.show_inherited_members:
+            return True  # show all class members
+        if name not in self._cls.__dict__:
+            return False  # class member is inherited, we do not show it
+        return True
diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py
index cdc2a37..1eaa6a9 100644
--- a/numpydoc/docscrape_sphinx.py
+++ b/numpydoc/docscrape_sphinx.py
@@ -1,8 +1,13 @@
 from __future__ import division, absolute_import, print_function
 
-import sys, re, inspect, textwrap, pydoc
+import sys
+import re
+import inspect
+import textwrap
+import pydoc
 import sphinx
 import collections
+
 from .docscrape import NumpyDocString, FunctionDoc, ClassDoc
 
 if sys.version_info[0] >= 3:
@@ -46,12 +51,12 @@ class SphinxDocString(NumpyDocString):
     def _str_extended_summary(self):
         return self['Extended Summary'] + ['']
 
-    def _str_returns(self):
+    def _str_returns(self, name='Returns'):
         out = []
-        if self['Returns']:
-            out += self._str_field_list('Returns')
+        if self[name]:
+            out += self._str_field_list(name)
             out += ['']
-            for param, param_type, desc in self['Returns']:
+            for param, param_type, desc in self[name]:
                 if param_type:
                     out += self._str_indent(['**%s** : %s' % (param.strip(),
                                                               param_type)])
@@ -130,7 +135,7 @@ class SphinxDocString(NumpyDocString):
                 maxlen_0 = max(3, max([len(x[0]) for x in others]))
                 hdr = sixu("=")*maxlen_0 + sixu("  ") + sixu("=")*10
                 fmt = sixu('%%%ds  %%s  ') % (maxlen_0,)
-                out += ['', hdr]
+                out += ['', '', hdr]
                 for param, param_type, desc in others:
                     desc = sixu(" ").join(x.strip() for x in desc).strip()
                     if param_type:
@@ -171,7 +176,7 @@ class SphinxDocString(NumpyDocString):
         if len(idx) == 0:
             return out
 
-        out += ['.. index:: %s' % idx.get('default','')]
+        out += ['.. index:: %s' % idx.get('default', '')]
         for section, references in idx.items():
             if section == 'default':
                 continue
@@ -192,9 +197,9 @@ class SphinxDocString(NumpyDocString):
             # Latex collects all references to a separate bibliography,
             # so we need to insert links to it
             if sphinx.__version__ >= "0.6":
-                out += ['.. only:: latex','']
+                out += ['.. only:: latex', '']
             else:
-                out += ['.. latexonly::','']
+                out += ['.. latexonly::', '']
             items = []
             for line in self['References']:
                 m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I)
@@ -224,7 +229,8 @@ class SphinxDocString(NumpyDocString):
         out += self._str_summary()
         out += self._str_extended_summary()
         out += self._str_param_list('Parameters')
-        out += self._str_returns()
+        out += self._str_returns('Returns')
+        out += self._str_returns('Yields')
         for param_list in ('Other Parameters', 'Raises', 'Warns'):
             out += self._str_param_list(param_list)
         out += self._str_warnings()
@@ -234,25 +240,29 @@ class SphinxDocString(NumpyDocString):
         out += self._str_examples()
         for param_list in ('Attributes', 'Methods'):
             out += self._str_member_list(param_list)
-        out = self._str_indent(out,indent)
+        out = self._str_indent(out, indent)
         return '\n'.join(out)
 
+
 class SphinxFunctionDoc(SphinxDocString, FunctionDoc):
     def __init__(self, obj, doc=None, config={}):
         self.load_config(config)
         FunctionDoc.__init__(self, obj, doc=doc, config=config)
 
+
 class SphinxClassDoc(SphinxDocString, ClassDoc):
     def __init__(self, obj, doc=None, func_doc=None, config={}):
         self.load_config(config)
         ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config)
 
+
 class SphinxObjDoc(SphinxDocString):
     def __init__(self, obj, doc=None, config={}):
         self._f = obj
         self.load_config(config)
         SphinxDocString.__init__(self, doc, config=config)
 
+
 def get_doc_object(obj, what=None, doc=None, config={}):
     if what is None:
         if inspect.isclass(obj):
diff --git a/numpydoc/linkcode.py b/numpydoc/linkcode.py
deleted file mode 100644
index 1ad3ab8..0000000
--- a/numpydoc/linkcode.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-    linkcode
-    ~~~~~~~~
-
-    Add external links to module code in Python object descriptions.
-
-    :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import warnings
-import collections
-
-warnings.warn("This extension has been accepted to Sphinx upstream. "
-              "Use the version from there (Sphinx >= 1.2) "
-              "https://bitbucket.org/birkenfeld/sphinx/pull-request/47/sphinxextlinkcode",
-              FutureWarning, stacklevel=1)
-
-
-from docutils import nodes
-
-from sphinx import addnodes
-from sphinx.locale import _
-from sphinx.errors import SphinxError
-
-class LinkcodeError(SphinxError):
-    category = "linkcode error"
-
-def doctree_read(app, doctree):
-    env = app.builder.env
-
-    resolve_target = getattr(env.config, 'linkcode_resolve', None)
-    if not isinstance(env.config.linkcode_resolve, collections.Callable):
-        raise LinkcodeError(
-            "Function `linkcode_resolve` is not given in conf.py")
-
-    domain_keys = dict(
-        py=['module', 'fullname'],
-        c=['names'],
-        cpp=['names'],
-        js=['object', 'fullname'],
-    )
-
-    for objnode in doctree.traverse(addnodes.desc):
-        domain = objnode.get('domain')
-        uris = set()
-        for signode in objnode:
-            if not isinstance(signode, addnodes.desc_signature):
-                continue
-
-            # Convert signode to a specified format
-            info = {}
-            for key in domain_keys.get(domain, []):
-                value = signode.get(key)
-                if not value:
-                    value = ''
-                info[key] = value
-            if not info:
-                continue
-
-            # Call user code to resolve the link
-            uri = resolve_target(domain, info)
-            if not uri:
-                # no source
-                continue
-
-            if uri in uris or not uri:
-                # only one link per name, please
-                continue
-            uris.add(uri)
-
-            onlynode = addnodes.only(expr='html')
-            onlynode += nodes.reference('', '', internal=False, refuri=uri)
-            onlynode[0] += nodes.inline('', _('[source]'),
-                                        classes=['viewcode-link'])
-            signode += onlynode
-
-def setup(app):
-    app.connect('doctree-read', doctree_read)
-    app.add_config_value('linkcode_resolve', None, '')
diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py
index 2bc2d1e..b9804ad 100644
--- a/numpydoc/numpydoc.py
+++ b/numpydoc/numpydoc.py
@@ -10,14 +10,17 @@ It will:
 - Convert Parameters etc. sections to field lists.
 - Convert See Also section to a See also entry.
 - Renumber references.
-- Extract the signature from the docstring, if it can't be determined otherwise.
+- Extract the signature from the docstring, if it can't be determined
+  otherwise.
 
 .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
 
 """
 from __future__ import division, absolute_import, print_function
 
-import os, sys, re, pydoc
+import sys
+import re
+import pydoc
 import sphinx
 import inspect
 import collections
@@ -37,26 +40,28 @@ else:
 def mangle_docstrings(app, what, name, obj, options, lines,
                       reference_offset=[0]):
 
-    cfg = dict(use_plots=app.config.numpydoc_use_plots,
-               show_class_members=app.config.numpydoc_show_class_members,
-               class_members_toctree=app.config.numpydoc_class_members_toctree,
-              )
+    cfg = {'use_plots': app.config.numpydoc_use_plots,
+           'show_class_members': app.config.numpydoc_show_class_members,
+           'show_inherited_class_members':
+           app.config.numpydoc_show_inherited_class_members,
+           'class_members_toctree': app.config.numpydoc_class_members_toctree}
 
+    u_NL = sixu('\n')
     if what == 'module':
         # Strip top title
-        title_re = re.compile(sixu('^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'),
-                              re.I|re.S)
-        lines[:] = title_re.sub(sixu(''), sixu("\n").join(lines)).split(sixu("\n"))
+        pattern = '^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'
+        title_re = re.compile(sixu(pattern), re.I | re.S)
+        lines[:] = title_re.sub(sixu(''), u_NL.join(lines)).split(u_NL)
     else:
-        doc = get_doc_object(obj, what, sixu("\n").join(lines), config=cfg)
+        doc = get_doc_object(obj, what, u_NL.join(lines), config=cfg)
         if sys.version_info[0] >= 3:
             doc = str(doc)
         else:
             doc = unicode(doc)
-        lines[:] = doc.split(sixu("\n"))
+        lines[:] = doc.split(u_NL)
 
-    if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
-           obj.__name__:
+    if (app.config.numpydoc_edit_link and hasattr(obj, '__name__') and
+            obj.__name__):
         if hasattr(obj, '__module__'):
             v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__))
         else:
@@ -89,24 +94,30 @@ def mangle_docstrings(app, what, name, obj, options, lines,
 
     reference_offset[0] += len(references)
 
+
 def mangle_signature(app, what, name, obj, options, sig, retann):
     # Do not try to inspect classes that don't define `__init__`
     if (inspect.isclass(obj) and
         (not hasattr(obj, '__init__') or
-        'initializes x; see ' in pydoc.getdoc(obj.__init__))):
+            'initializes x; see ' in pydoc.getdoc(obj.__init__))):
         return '', ''
 
-    if not (isinstance(obj, collections.Callable) or hasattr(obj, '__argspec_is_invalid_')): return
-    if not hasattr(obj, '__doc__'): return
+    if not (isinstance(obj, collections.Callable) or
+            hasattr(obj, '__argspec_is_invalid_')):
+        return
+
+    if not hasattr(obj, '__doc__'):
+        return
 
     doc = SphinxDocString(pydoc.getdoc(obj))
     if doc['Signature']:
         sig = re.sub(sixu("^[^(]*"), sixu(""), doc['Signature'])
         return sig, sixu('')
 
+
 def setup(app, get_doc_object_=get_doc_object):
     if not hasattr(app, 'add_config_value'):
-        return # probably called by nose, better bail out
+        return  # probably called by nose, better bail out
 
     global get_doc_object
     get_doc_object = get_doc_object_
@@ -116,20 +127,25 @@ def setup(app, get_doc_object_=get_doc_object):
     app.add_config_value('numpydoc_edit_link', None, False)
     app.add_config_value('numpydoc_use_plots', None, False)
     app.add_config_value('numpydoc_show_class_members', True, True)
+    app.add_config_value('numpydoc_show_inherited_class_members', True, True)
     app.add_config_value('numpydoc_class_members_toctree', True, True)
 
     # Extra mangling domains
     app.add_domain(NumpyPythonDomain)
     app.add_domain(NumpyCDomain)
+    
+    metadata = {'parallel_read_safe': True}
+    return metadata
 
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
 # Docstring-mangling domains
-#------------------------------------------------------------------------------
+# ------------------------------------------------------------------------------
 
 from docutils.statemachine import ViewList
 from sphinx.domains.c import CDomain
 from sphinx.domains.python import PythonDomain
 
+
 class ManglingDomainBase(object):
     directive_mangling_map = {}
 
@@ -142,6 +158,7 @@ class ManglingDomainBase(object):
             self.directives[name] = wrap_mangling_directive(
                 self.directives[name], objtype)
 
+
 class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
     name = 'np'
     directive_mangling_map = {
@@ -155,6 +172,7 @@ class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
     }
     indices = []
 
+
 class NumpyCDomain(ManglingDomainBase, CDomain):
     name = 'np-c'
     directive_mangling_map = {
@@ -165,6 +183,7 @@ class NumpyCDomain(ManglingDomainBase, CDomain):
         'var': 'object',
     }
 
+
 def wrap_mangling_directive(base_directive, objtype):
     class directive(base_directive):
         def run(self):
diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py
index b682504..634bef4 100644
--- a/numpydoc/tests/test_docscrape.py
+++ b/numpydoc/tests/test_docscrape.py
@@ -122,6 +122,20 @@ doc_txt = '''\
   '''
 doc = NumpyDocString(doc_txt)
 
+doc_yields_txt = """
+Test generator
+
+Yields
+------
+a : int
+    The number of apples.
+b : int
+    The number of bananas.
+int
+    The number of unknowns.
+"""
+doc_yields = NumpyDocString(doc_yields_txt)
+
 
 def test_signature():
     assert doc['Signature'].startswith('numpy.multivariate_normal(')
@@ -164,6 +178,37 @@ def test_returns():
     assert desc[0].startswith('This is not a real')
     assert desc[-1].endswith('anonymous return values.')
 
+def test_yields():
+    section = doc_yields['Yields']
+    assert_equal(len(section), 3)
+    truth = [('a', 'int', 'apples.'),
+             ('b', 'int', 'bananas.'),
+             ('int', '', 'unknowns.')]
+    for (arg, arg_type, desc), (arg_, arg_type_, end) in zip(section, truth):
+        assert_equal(arg, arg_)
+        assert_equal(arg_type, arg_type_)
+        assert desc[0].startswith('The number of')
+        assert desc[0].endswith(end)
+
+def test_returnyield():
+    doc_text = """
+Test having returns and yields.
+
+Returns
+-------
+int
+    The number of apples.
+
+Yields
+------
+a : int
+    The number of apples.
+b : int
+    The number of bananas.
+
+"""
+    assert_raises(ValueError, NumpyDocString, doc_text)
+
 def test_notes():
     assert doc['Notes'][0].startswith('Instead')
     assert doc['Notes'][-1].endswith('definite.')
@@ -193,6 +238,9 @@ def non_blank_line_by_line_compare(a,b):
                                  "\n>>> %s\n<<< %s\n" %
                                  (n,line,b[n]))
 def test_str():
+    # doc_txt has the order of Notes and See Also sections flipped.
+    # This should be handled automatically, and so, one thing this test does
+    # is to make sure that See Also precedes Notes in the output.
     non_blank_line_by_line_compare(str(doc),
 """numpy.multivariate_normal(mean, cov, shape=None, spam=None)
 
@@ -302,6 +350,22 @@ standard deviation:
    :refguide: random;distributions, random;gauss""")
 
 
+def test_yield_str():
+    non_blank_line_by_line_compare(str(doc_yields),
+"""Test generator
+
+Yields
+------
+a : int
+    The number of apples.
+b : int
+    The number of bananas.
+int
+    The number of unknowns.
+
+.. index:: """)
+
+
 def test_sphinx_str():
     sphinx_doc = SphinxDocString(doc_txt)
     non_blank_line_by_line_compare(str(sphinx_doc),
@@ -427,6 +491,27 @@ standard deviation:
 """)
 
 
+def test_sphinx_yields_str():
... 219 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/numpydoc.git



More information about the Python-modules-commits mailing list