[Python-modules-commits] [numpydoc] 01/04: Import numpydoc_0.5.orig.tar.gz

Denis Laxalde dlax-guest at moszumanska.debian.org
Sun Oct 25 10:30:02 UTC 2015


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

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

commit bde59512f89b264e6bb00cc9f353bbdf177bf18b
Author: Denis Laxalde <denis at laxalde.org>
Date:   Wed Oct 21 21:31:20 2015 +0200

    Import numpydoc_0.5.orig.tar.gz
---
 LICENSE.txt                                        |   7 +-
 MANIFEST.in                                        |   2 +-
 PKG-INFO                                           |   7 +-
 README.txt => README.rst                           |  12 ++
 __init__.py                                        |   1 -
 numpydoc.egg-info/PKG-INFO                         |   7 +-
 numpydoc.egg-info/SOURCES.txt                      |  30 +--
 numpydoc.egg-info/entry_points.txt                 |   3 -
 numpydoc.egg-info/not-zip-safe                     |   1 -
 numpydoc.egg-info/requires.txt                     |   1 -
 numpydoc/__init__.py                               |   3 +
 comment_eater.py => numpydoc/comment_eater.py      |  19 +-
 .../compiler_unparse.py                            |  27 +--
 docscrape.py => numpydoc/docscrape.py              |  77 +++++---
 .../docscrape_sphinx.py                            |  97 +++++++---
 numpydoc/linkcode.py                               |  83 +++++++++
 numpydoc.py => numpydoc/numpydoc.py                |  73 +++++---
 phantom_import.py => numpydoc/phantom_import.py    |   9 +-
 plot_directive.py => numpydoc/plot_directive.py    | 117 +++++++-----
 {tests => numpydoc/tests}/test_docscrape.py        | 204 ++++++++++++++++++---
 numpydoc/tests/test_linkcode.py                    |   5 +
 numpydoc/tests/test_phantom_import.py              |  12 ++
 numpydoc/tests/test_plot_directive.py              |  11 ++
 numpydoc/tests/test_traitsdoc.py                   |  11 ++
 traitsdoc.py => numpydoc/traitsdoc.py              |  14 +-
 setup.py                                           |  25 ++-
 26 files changed, 644 insertions(+), 214 deletions(-)

diff --git a/LICENSE.txt b/LICENSE.txt
index e00efc3..b15c699 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -1,8 +1,6 @@
 -------------------------------------------------------------------------------
     The files
     - numpydoc.py
-    - autosummary.py
-    - autosummary_generate.py
     - docscrape.py
     - docscrape_sphinx.py
     - phantom_import.py
@@ -71,10 +69,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
 -------------------------------------------------------------------------------
-    The files
-    - only_directives.py
+    The file
     - plot_directive.py
-    originate from Matplotlib (http://matplotlib.sf.net/) which has
+    originates from Matplotlib (http://matplotlib.sf.net/) which has
     the following license:
 
 Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved.
diff --git a/MANIFEST.in b/MANIFEST.in
index f88ed78..5176d48 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,2 +1,2 @@
-recursive-include tests *.py
+recursive-include numpydoc/tests *.py
 include *.txt
diff --git a/PKG-INFO b/PKG-INFO
index e1aa2f2..c363407 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,8 +1,8 @@
-Metadata-Version: 1.0
+Metadata-Version: 1.1
 Name: numpydoc
-Version: 0.4
+Version: 0.5
 Summary: Sphinx extension to support docstrings in Numpy format
-Home-page: http://github.com/numpy/numpy/tree/master/doc/sphinxext
+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
@@ -13,3 +13,4 @@ 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/README.txt b/README.rst
similarity index 73%
rename from README.txt
rename to README.rst
index 6ba63e6..e2711e1 100644
--- a/README.txt
+++ b/README.rst
@@ -1,3 +1,6 @@
+.. image:: https://travis-ci.org/numpy/numpydoc.png?branch=master
+   :target: https://travis-ci.org/numpy/numpydoc/
+
 =====================================
 numpydoc -- Numpy's Sphinx extensions
 =====================================
@@ -18,6 +21,9 @@ The following extensions are available:
     directive. Note that this implementation may still undergo severe
     changes or eventually be deprecated.
 
+See `A Guide to NumPy/SciPy Documentation <https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`_
+for how to write docs that use this extension.
+
 
 numpydoc
 ========
@@ -40,6 +46,12 @@ The following options can be set in conf.py:
   Whether to show all members of a class in the Methods and Attributes
   sections automatically.
 
+- 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.
+
 - numpydoc_edit_link: bool  (DEPRECATED -- edit your HTML template instead)
 
   Whether to insert an edit link after docstrings.
diff --git a/__init__.py b/__init__.py
deleted file mode 100644
index ae9073b..0000000
--- a/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from numpydoc import setup
diff --git a/numpydoc.egg-info/PKG-INFO b/numpydoc.egg-info/PKG-INFO
index e1aa2f2..c363407 100644
--- a/numpydoc.egg-info/PKG-INFO
+++ b/numpydoc.egg-info/PKG-INFO
@@ -1,8 +1,8 @@
-Metadata-Version: 1.0
+Metadata-Version: 1.1
 Name: numpydoc
-Version: 0.4
+Version: 0.5
 Summary: Sphinx extension to support docstrings in Numpy format
-Home-page: http://github.com/numpy/numpy/tree/master/doc/sphinxext
+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
@@ -13,3 +13,4 @@ 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
index 1a277df..b6246c0 100644
--- a/numpydoc.egg-info/SOURCES.txt
+++ b/numpydoc.egg-info/SOURCES.txt
@@ -1,21 +1,23 @@
 LICENSE.txt
 MANIFEST.in
-README.txt
-__init__.py
-comment_eater.py
-compiler_unparse.py
-docscrape.py
-docscrape_sphinx.py
-numpydoc.py
-phantom_import.py
-plot_directive.py
+README.rst
 setup.py
-traitsdoc.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/entry_points.txt
-numpydoc.egg-info/not-zip-safe
-numpydoc.egg-info/requires.txt
 numpydoc.egg-info/top_level.txt
-tests/test_docscrape.py
\ No newline at end of file
+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/entry_points.txt b/numpydoc.egg-info/entry_points.txt
deleted file mode 100644
index 8abd140..0000000
--- a/numpydoc.egg-info/entry_points.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-[console_scripts]
-autosummary_generate = numpydoc.autosummary_generate:main
-
diff --git a/numpydoc.egg-info/not-zip-safe b/numpydoc.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/numpydoc.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/numpydoc.egg-info/requires.txt b/numpydoc.egg-info/requires.txt
deleted file mode 100644
index c95829d..0000000
--- a/numpydoc.egg-info/requires.txt
+++ /dev/null
@@ -1 +0,0 @@
-Sphinx >= 1.0.1
\ No newline at end of file
diff --git a/numpydoc/__init__.py b/numpydoc/__init__.py
new file mode 100644
index 0000000..0fce2cf
--- /dev/null
+++ b/numpydoc/__init__.py
@@ -0,0 +1,3 @@
+from __future__ import division, absolute_import, print_function
+
+from .numpydoc import setup
diff --git a/comment_eater.py b/numpydoc/comment_eater.py
similarity index 93%
rename from comment_eater.py
rename to numpydoc/comment_eater.py
index e11eea9..8cddd33 100644
--- a/comment_eater.py
+++ b/numpydoc/comment_eater.py
@@ -1,10 +1,17 @@
-from cStringIO import StringIO
+from __future__ import division, absolute_import, print_function
+
+import sys
+if sys.version_info[0] >= 3:
+    from io import StringIO
+else:
+    from io import StringIO
+
 import compiler
 import inspect
 import textwrap
 import tokenize
 
-from compiler_unparse import unparse
+from .compiler_unparse import unparse
 
 
 class Comment(object):
@@ -68,7 +75,11 @@ class CommentBlocker(object):
     def process_file(self, file):
         """ Process a file object.
         """
-        for token in tokenize.generate_tokens(file.next):
+        if sys.version_info[0] >= 3:
+            nxt = file.__next__
+        else:
+            nxt = file.next
+        for token in tokenize.generate_tokens(nxt):
             self.process_token(*token)
         self.make_index()
 
@@ -95,7 +106,7 @@ class CommentBlocker(object):
 
     def new_comment(self, string, start, end, line):
         """ Possibly add a new comment.
-        
+
         Only adds a new comment if this comment is the only thing on the line.
         Otherwise, it extends the noncomment block.
         """
diff --git a/compiler_unparse.py b/numpydoc/compiler_unparse.py
similarity index 99%
rename from compiler_unparse.py
rename to numpydoc/compiler_unparse.py
index ffcf51b..8933a83 100644
--- a/compiler_unparse.py
+++ b/numpydoc/compiler_unparse.py
@@ -10,13 +10,18 @@
     fixme: We may want to move to using _ast trees because the compiler for
            them is about 6 times faster than compiler.compile.
 """
+from __future__ import division, absolute_import, print_function
 
 import sys
-import cStringIO
 from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add
 
+if sys.version_info[0] >= 3:
+    from io import StringIO
+else:
+    from StringIO import StringIO
+
 def unparse(ast, single_line_functions=False):
-    s = cStringIO.StringIO()
+    s = StringIO()
     UnparseCompilerAst(ast, s, single_line_functions)
     return s.getvalue().lstrip()
 
@@ -101,13 +106,13 @@ class UnparseCompilerAst:
             if i != len(t.nodes)-1:
                 self._write(") and (")
         self._write(")")
-               
+
     def _AssAttr(self, t):
         """ Handle assigning an attribute of an object
         """
         self._dispatch(t.expr)
         self._write('.'+t.attrname)
- 
+
     def _Assign(self, t):
         """ Expression Assignment such as "a = 1".
 
@@ -145,36 +150,36 @@ class UnparseCompilerAst:
     def _AugAssign(self, t):
         """ +=,-=,*=,/=,**=, etc. operations
         """
-        
+
         self._fill()
         self._dispatch(t.node)
         self._write(' '+t.op+' ')
         self._dispatch(t.expr)
         if not self._do_indent:
             self._write(';')
-            
+
     def _Bitand(self, t):
         """ Bit and operation.
         """
-        
+
         for i, node in enumerate(t.nodes):
             self._write("(")
             self._dispatch(node)
             self._write(")")
             if i != len(t.nodes)-1:
                 self._write(" & ")
-                
+
     def _Bitor(self, t):
         """ Bit or operation
         """
-        
+
         for i, node in enumerate(t.nodes):
             self._write("(")
             self._dispatch(node)
             self._write(")")
             if i != len(t.nodes)-1:
                 self._write(" | ")
-                
+
     def _CallFunc(self, t):
         """ Function call.
         """
@@ -249,7 +254,7 @@ class UnparseCompilerAst:
             self._write(name)
             if asname is not None:
                 self._write(" as "+asname)
-                
+
     def _Function(self, t):
         """ Handle function definitions
         """
diff --git a/docscrape.py b/numpydoc/docscrape.py
similarity index 86%
rename from docscrape.py
rename to numpydoc/docscrape.py
index 615ea11..2b1719d 100644
--- a/docscrape.py
+++ b/numpydoc/docscrape.py
@@ -1,13 +1,16 @@
 """Extract reference documentation from the NumPy source tree.
 
 """
+from __future__ import division, absolute_import, print_function
 
 import inspect
 import textwrap
 import re
 import pydoc
-from StringIO import StringIO
 from warnings import warn
+import collections
+import sys
+
 
 class Reader(object):
     """A line-based string reader.
@@ -113,7 +116,7 @@ class NumpyDocString(object):
         return self._parsed_data[key]
 
     def __setitem__(self,key,val):
-        if not self._parsed_data.has_key(key):
+        if key not in self._parsed_data:
             warn("Unknown section %s" % key)
         else:
             self._parsed_data[key] = val
@@ -265,13 +268,17 @@ class NumpyDocString(object):
         if self._is_at_section():
             return
 
-        summary = self._doc.read_to_next_empty_line()
-        summary_str = " ".join([s.strip() for s in summary]).strip()
-        if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str):
-            self['Signature'] = summary_str
-            if not self._is_at_section():
-                self['Summary'] = self._doc.read_to_next_empty_line()
-        else:
+        # If several signatures present, take the last one
+        while True:
+            summary = self._doc.read_to_next_empty_line()
+            summary_str = " ".join([s.strip() for s in summary]).strip()
+            if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str):
+                self['Signature'] = summary_str
+                if not self._is_at_section():
+                    continue
+            break
+
+        if summary is not None:
             self['Summary'] = summary
 
         if not self._is_at_section():
@@ -328,7 +335,10 @@ class NumpyDocString(object):
         if self[name]:
             out += self._str_header(name)
             for param,param_type,desc in self[name]:
-                out += ['%s : %s' % (param, param_type)]
+                if param_type:
+                    out += ['%s : %s' % (param, param_type)]
+                else:
+                    out += [param]
                 out += self._str_indent(desc)
             out += ['']
         return out
@@ -370,7 +380,7 @@ class NumpyDocString(object):
         idx = self['index']
         out = []
         out += ['.. index:: %s' % idx.get('default','')]
-        for section, references in idx.iteritems():
+        for section, references in idx.items():
             if section == 'default':
                 continue
             out += ['   :%s: %s' % (section, ', '.join(references))]
@@ -424,11 +434,14 @@ class FunctionDoc(NumpyDocString):
             func, func_name = self.get_func()
             try:
                 # try to read signature
-                argspec = inspect.getargspec(func)
+                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, e:
+            except TypeError as e:
                 signature = '%s()' % func_name
             self['Signature'] = signature
 
@@ -450,8 +463,8 @@ class FunctionDoc(NumpyDocString):
                  'meth': 'method'}
 
         if self._role:
-            if not roles.has_key(self._role):
-                print "Warning: invalid role %s" % 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,''),
                                              func_name)
 
@@ -460,6 +473,9 @@ class FunctionDoc(NumpyDocString):
 
 
 class ClassDoc(NumpyDocString):
+
+    extra_public_methods = ['__call__']
+
     def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
                  config={}):
         if not inspect.isclass(cls) and cls is not None:
@@ -478,23 +494,38 @@ class ClassDoc(NumpyDocString):
         NumpyDocString.__init__(self, doc)
 
         if config.get('show_class_members', True):
-            if not self['Methods']:
-                self['Methods'] = [(name, '', '')
-                                   for name in sorted(self.methods)]
-            if not self['Attributes']:
-                self['Attributes'] = [(name, '', '')
-                                      for name in sorted(self.properties)]
+            def splitlines_x(s):
+                if not s:
+                    return []
+                else:
+                    return s.splitlines()
+
+            for field, items in [('Methods', self.methods),
+                                 ('Attributes', self.properties)]:
+                if not self[field]:
+                    doc_list = []
+                    for name in sorted(items):
+                         try:
+                            doc_item = pydoc.getdoc(getattr(self._cls, name))
+                            doc_list.append((name, '', splitlines_x(doc_item)))
+                         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)
-                if not name.startswith('_') and callable(func)]
+                if ((not name.startswith('_')
+                     or name in self.extra_public_methods)
+                    and isinstance(func, collections.Callable))]
 
     @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]
+                if not name.startswith('_') and
+                (func is None or isinstance(func, property) or
+                 inspect.isgetsetdescriptor(func))]
diff --git a/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py
similarity index 68%
rename from docscrape_sphinx.py
rename to numpydoc/docscrape_sphinx.py
index e44e770..cdc2a37 100644
--- a/docscrape_sphinx.py
+++ b/numpydoc/docscrape_sphinx.py
@@ -1,11 +1,24 @@
-import re, inspect, textwrap, pydoc
+from __future__ import division, absolute_import, print_function
+
+import sys, re, inspect, textwrap, pydoc
 import sphinx
-from docscrape import NumpyDocString, FunctionDoc, ClassDoc
+import collections
+from .docscrape import NumpyDocString, FunctionDoc, ClassDoc
+
+if sys.version_info[0] >= 3:
+    sixu = lambda s: s
+else:
+    sixu = lambda s: unicode(s, 'unicode_escape')
+
 
 class SphinxDocString(NumpyDocString):
     def __init__(self, docstring, config={}):
-        self.use_plots = config.get('use_plots', False)
         NumpyDocString.__init__(self, docstring, config=config)
+        self.load_config(config)
+
+    def load_config(self, config):
+        self.use_plots = config.get('use_plots', False)
+        self.class_members_toctree = config.get('class_members_toctree', True)
 
     # string conversion routines
     def _str_header(self, name, symbol='`'):
@@ -33,16 +46,37 @@ class SphinxDocString(NumpyDocString):
     def _str_extended_summary(self):
         return self['Extended Summary'] + ['']
 
+    def _str_returns(self):
+        out = []
+        if self['Returns']:
+            out += self._str_field_list('Returns')
+            out += ['']
+            for param, param_type, desc in self['Returns']:
+                if param_type:
+                    out += self._str_indent(['**%s** : %s' % (param.strip(),
+                                                              param_type)])
+                else:
+                    out += self._str_indent([param.strip()])
+                if desc:
+                    out += ['']
+                    out += self._str_indent(desc, 8)
+                out += ['']
+        return out
+
     def _str_param_list(self, name):
         out = []
         if self[name]:
             out += self._str_field_list(name)
             out += ['']
-            for param,param_type,desc in self[name]:
-                out += self._str_indent(['**%s** : %s' % (param.strip(),
-                                                          param_type)])
-                out += ['']
-                out += self._str_indent(desc,8)
+            for param, param_type, desc in self[name]:
+                if param_type:
+                    out += self._str_indent(['**%s** : %s' % (param.strip(),
+                                                              param_type)])
+                else:
+                    out += self._str_indent(['**%s**' % param.strip()])
+                if desc:
+                    out += ['']
+                    out += self._str_indent(desc, 8)
                 out += ['']
         return out
 
@@ -72,25 +106,36 @@ class SphinxDocString(NumpyDocString):
             others = []
             for param, param_type, desc in self[name]:
                 param = param.strip()
-                if not self._obj or hasattr(self._obj, param):
+
+                # Check if the referenced member can have a docstring or not
+                param_obj = getattr(self._obj, param, None)
+                if not (callable(param_obj)
+                        or isinstance(param_obj, property)
+                        or inspect.isgetsetdescriptor(param_obj)):
+                    param_obj = None
+
+                if param_obj and (pydoc.getdoc(param_obj) or not desc):
+                    # Referenced object has a docstring
                     autosum += ["   %s%s" % (prefix, param)]
                 else:
                     others.append((param, param_type, desc))
 
             if autosum:
-                out += ['.. autosummary::', '   :toctree:', '']
-                out += autosum
+                out += ['.. autosummary::']
+                if self.class_members_toctree:
+                    out += ['   :toctree:']
+                out += [''] + autosum
 
             if others:
-                maxlen_0 = max([len(x[0]) for x in others])
-                maxlen_1 = max([len(x[1]) for x in others])
-                hdr = "="*maxlen_0 + "  " + "="*maxlen_1 + "  " + "="*10
-                fmt = '%%%ds  %%%ds  ' % (maxlen_0, maxlen_1)
-                n_indent = maxlen_0 + maxlen_1 + 4
-                out += [hdr]
+                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]
                 for param, param_type, desc in others:
-                    out += [fmt % (param.strip(), param_type)]
-                    out += self._str_indent(desc, n_indent)
+                    desc = sixu(" ").join(x.strip() for x in desc).strip()
+                    if param_type:
+                        desc = "(%s) %s" % (param_type, desc)
+                    out += [fmt % (param.strip(), desc)]
                 out += [hdr]
             out += ['']
         return out
@@ -127,7 +172,7 @@ class SphinxDocString(NumpyDocString):
             return out
 
         out += ['.. index:: %s' % idx.get('default','')]
-        for section, references in idx.iteritems():
+        for section, references in idx.items():
             if section == 'default':
                 continue
             elif section == 'refguide':
@@ -178,8 +223,9 @@ class SphinxDocString(NumpyDocString):
         out += self._str_index() + ['']
         out += self._str_summary()
         out += self._str_extended_summary()
-        for param_list in ('Parameters', 'Returns', 'Other Parameters',
-                           'Raises', 'Warns'):
+        out += self._str_param_list('Parameters')
+        out += self._str_returns()
+        for param_list in ('Other Parameters', 'Raises', 'Warns'):
             out += self._str_param_list(param_list)
         out += self._str_warnings()
         out += self._str_see_also(func_role)
@@ -193,17 +239,18 @@ class SphinxDocString(NumpyDocString):
 
 class SphinxFunctionDoc(SphinxDocString, FunctionDoc):
     def __init__(self, obj, doc=None, config={}):
-        self.use_plots = config.get('use_plots', False)
+        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.use_plots = config.get('use_plots', False)
+        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={}):
@@ -212,7 +259,7 @@ def get_doc_object(obj, what=None, doc=None, config={}):
             what = 'class'
         elif inspect.ismodule(obj):
             what = 'module'
-        elif callable(obj):
+        elif isinstance(obj, collections.Callable):
             what = 'function'
         else:
             what = 'object'
diff --git a/numpydoc/linkcode.py b/numpydoc/linkcode.py
new file mode 100644
index 0000000..1ad3ab8
--- /dev/null
+++ b/numpydoc/linkcode.py
@@ -0,0 +1,83 @@
+# -*- 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.py b/numpydoc/numpydoc.py
similarity index 66%
rename from numpydoc.py
rename to numpydoc/numpydoc.py
index aa39005..2bc2d1e 100644
--- a/numpydoc.py
+++ b/numpydoc/numpydoc.py
@@ -12,45 +12,64 @@ It will:
 - Renumber references.
 - Extract the signature from the docstring, if it can't be determined otherwise.
 
-.. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard
+.. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
 
 """
+from __future__ import division, absolute_import, print_function
 
-import os, re, pydoc
-from docscrape_sphinx import get_doc_object, SphinxDocString
-from sphinx.util.compat import Directive
+import os, sys, re, pydoc
+import sphinx
 import inspect
+import collections
+
+if sphinx.__version__ < '1.0.1':
+    raise RuntimeError("Sphinx 1.0.1 or newer is required")
+
+from .docscrape_sphinx import get_doc_object, SphinxDocString
+from sphinx.util.compat import Directive
+
+if sys.version_info[0] >= 3:
+    sixu = lambda s: s
+else:
+    sixu = lambda s: unicode(s, 'unicode_escape')
+
 
 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)
+               show_class_members=app.config.numpydoc_show_class_members,
+               class_members_toctree=app.config.numpydoc_class_members_toctree,
+              )
 
     if what == 'module':
         # Strip top title
-        title_re = re.compile(ur'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*',
+        title_re = re.compile(sixu('^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'),
                               re.I|re.S)
-        lines[:] = title_re.sub(u'', u"\n".join(lines)).split(u"\n")
+        lines[:] = title_re.sub(sixu(''), sixu("\n").join(lines)).split(sixu("\n"))
     else:
-        doc = get_doc_object(obj, what, u"\n".join(lines), config=cfg)
-        lines[:] = unicode(doc).split(u"\n")
+        doc = get_doc_object(obj, what, sixu("\n").join(lines), config=cfg)
+        if sys.version_info[0] >= 3:
+            doc = str(doc)
+        else:
+            doc = unicode(doc)
+        lines[:] = doc.split(sixu("\n"))
 
     if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
            obj.__name__:
         if hasattr(obj, '__module__'):
-            v = dict(full_name=u"%s.%s" % (obj.__module__, obj.__name__))
+            v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__))
         else:
             v = dict(full_name=obj.__name__)
-        lines += [u'', u'.. htmlonly::', '']
-        lines += [u'    %s' % x for x in
+        lines += [sixu(''), sixu('.. htmlonly::'), sixu('')]
+        lines += [sixu('    %s') % x for x in
                   (app.config.numpydoc_edit_link % v).split("\n")]
 
     # replace reference numbers so that there are no duplicates
     references = []
     for line in lines:
         line = line.strip()
-        m = re.match(ur'^.. \[([a-z0-9_.-])\]', line, re.I)
+        m = re.match(sixu('^.. \\[([a-z0-9_.-])\\]'), line, re.I)
         if m:
             references.append(m.group(1))
 
@@ -59,14 +78,14 @@ def mangle_docstrings(app, what, name, obj, options, lines,
     if references:
         for i, line in enumerate(lines):
             for r in references:
-                if re.match(ur'^\d+$', r):
-                    new_r = u"R%d" % (reference_offset[0] + int(r))
+                if re.match(sixu('^\\d+$'), r):
+                    new_r = sixu("R%d") % (reference_offset[0] + int(r))
                 else:
-                    new_r = u"%s%d" % (r, reference_offset[0])
-                lines[i] = lines[i].replace(u'[%s]_' % r,
-                                            u'[%s]_' % new_r)
-                lines[i] = lines[i].replace(u'.. [%s]' % r,
-                                            u'.. [%s]' % new_r)
+                    new_r = sixu("%s%d") % (r, reference_offset[0])
+                lines[i] = lines[i].replace(sixu('[%s]_') % r,
+                                            sixu('[%s]_') % new_r)
+                lines[i] = lines[i].replace(sixu('.. [%s]') % r,
+                                            sixu('.. [%s]') % new_r)
 
     reference_offset[0] += len(references)
 
@@ -77,15 +96,18 @@ def mangle_signature(app, what, name, obj, options, sig, retann):
         'initializes x; see ' in pydoc.getdoc(obj.__init__))):
         return '', ''
 
-    if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): 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(u"^[^(]*", u"", doc['Signature'])
-        return sig, u''
+        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
+
     global get_doc_object
     get_doc_object = get_doc_object_
 
@@ -94,6 +116,7 @@ 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_class_members_toctree', True, True)
 
     # Extra mangling domains
     app.add_domain(NumpyPythonDomain)
@@ -115,7 +138,7 @@ class ManglingDomainBase(object):
         self.wrap_mangling_directives()
 
     def wrap_mangling_directives(self):
-        for name, objtype in self.directive_mangling_map.items():
+        for name, objtype in list(self.directive_mangling_map.items()):
             self.directives[name] = wrap_mangling_directive(
                 self.directives[name], objtype)
 
@@ -130,6 +153,7 @@ class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
         'staticmethod': 'function',
         'attribute': 'attribute',
     }
+    indices = []
 
 class NumpyCDomain(ManglingDomainBase, CDomain):
     name = 'np-c'
@@ -161,4 +185,3 @@ def wrap_mangling_directive(base_directive, objtype):
             return base_directive.run(self)
 
     return directive
-
diff --git a/phantom_import.py b/numpydoc/phantom_import.py
similarity index 95%
rename from phantom_import.py
rename to numpydoc/phantom_import.py
index c77eeb5..9a60b4a 100644
--- a/phantom_import.py
+++ b/numpydoc/phantom_import.py
@@ -14,6 +14,8 @@ without needing to rebuild the documented module.
 .. [1] http://code.google.com/p/pydocweb
 
 """
+from __future__ import division, absolute_import, print_function
+
 import imp, sys, compiler, types, os, inspect, re
 
 def setup(app):
@@ -23,7 +25,7 @@ def setup(app):
 def initialize(app):
     fn = app.config.phantom_import_file
     if (fn and os.path.isfile(fn)):
-        print "[numpydoc] Phantom importing modules from", fn, "..."
+        print("[numpydoc] Phantom importing modules from", fn, "...")
         import_phantom_module(fn)
 
 #------------------------------------------------------------------------------
@@ -129,7 +131,10 @@ def import_phantom_module(xml_file):
                 doc = "%s%s\n\n%s" % (funcname, argspec, doc)
             obj = lambda: 0
             obj.__argspec_is_invalid_ = True
-            obj.func_name = funcname
+            if sys.version_info[0] >= 3:
+                obj.__name__ = funcname
+            else:
+                obj.func_name = funcname
... 733 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