예제 #1
0
파일: conf.py 프로젝트: LLx2/pandas
 def resolve_name(self, modname, parents, path, base):
     if modname is None:
         if path:
             mod_cls = path.rstrip('.')
         else:
             mod_cls = None
             # if documenting a class-level object without path,
             # there must be a current class, either from a parent
             # auto directive ...
             mod_cls = self.env.temp_data.get('autodoc:class')
             # ... or from a class directive
             if mod_cls is None:
                 mod_cls = self.env.temp_data.get('py:class')
             # ... if still None, there's no way to know
             if mod_cls is None:
                 return None, []
         # HACK: this is added in comparison to ClassLevelDocumenter
         # mod_cls still exists of class.accessor, so an extra
         # rpartition is needed
         modname, accessor = rpartition(mod_cls, '.')
         modname, cls = rpartition(modname, '.')
         parents = [cls, accessor]
         # if the module name is still missing, get it like above
         if not modname:
             modname = self.env.temp_data.get('autodoc:module')
         if not modname:
             if sphinx.__version__ > '1.3':
                 modname = self.env.ref_context.get('py:module')
             else:
                 modname = self.env.temp_data.get('py:module')
         # ... else, it stays None, which means invalid
     return modname, parents + [base]
예제 #2
0
 def resolve_name(self, modname, parents, path, base):
     if modname is None:
         if path:
             mod_cls = path.rstrip(".")
         else:
             mod_cls = None
             # if documenting a class-level object without path,
             # there must be a current class, either from a parent
             # auto directive ...
             mod_cls = self.env.temp_data.get("autodoc:class")
             # ... or from a class directive
             if mod_cls is None:
                 mod_cls = self.env.temp_data.get("py:class")
             # ... if still None, there's no way to know
             if mod_cls is None:
                 return None, []
         # HACK: this is added in comparison to ClassLevelDocumenter
         # mod_cls still exists of class.accessor, so an extra
         # rpartition is needed
         modname, accessor = rpartition(mod_cls, ".")
         modname, cls = rpartition(modname, ".")
         parents = [cls, accessor]
         # if the module name is still missing, get it like above
         if not modname:
             modname = self.env.temp_data.get("autodoc:module")
         if not modname:
             if sphinx.__version__ > "1.3":
                 modname = self.env.ref_context.get("py:module")
             else:
                 modname = self.env.temp_data.get("py:module")
         # ... else, it stays None, which means invalid
     return modname, parents + [base]
예제 #3
0
 def get_objects(self, fn2index):
     rv = {}
     otypes = self._objtypes
     onames = self._objnames
     for domainname, domain in self.env.domains.iteritems():
         for fullname, dispname, type, docname, anchor, prio in \
                 domain.get_objects():
             # XXX use dispname?
             if docname not in fn2index:
                 continue
             if prio < 0:
                 continue
             # XXX splitting at dot is kind of Python specific
             prefix, name = rpartition(fullname, '.')
             pdict = rv.setdefault(prefix, {})
             try:
                 i = otypes[domainname, type]
             except KeyError:
                 i = len(otypes)
                 otypes[domainname, type] = i
                 otype = domain.object_types.get(type)
                 if otype:
                     # use unicode() to fire translation proxies
                     onames[i] = unicode(domain.get_type_name(otype))
                 else:
                     onames[i] = type
             pdict[name] = (fn2index[docname], i, prio)
     return rv
예제 #4
0
 def get_objects(self, fn2index):
     rv = {}
     otypes = self._objtypes
     onames = self._objnames
     for domainname, domain in sorted(iteritems(self.env.domains)):
         for fullname, dispname, type, docname, anchor, prio in \
                 sorted(domain.get_objects()):
             # XXX use dispname?
             if docname not in fn2index:
                 continue
             if prio < 0:
                 continue
             fullname = htmlescape(fullname)
             prefix, name = rpartition(fullname, '.')
             pdict = rv.setdefault(prefix, {})
             try:
                 typeindex = otypes[domainname, type]
             except KeyError:
                 typeindex = len(otypes)
                 otypes[domainname, type] = typeindex
                 otype = domain.object_types.get(type)
                 if otype:
                     # use unicode() to fire translation proxies
                     onames[typeindex] = (domainname, type,
                                          text_type(domain.get_type_name(otype)))
                 else:
                     onames[typeindex] = (domainname, type, type)
             if anchor == fullname:
                 shortanchor = ''
             elif anchor == type + '-' + fullname:
                 shortanchor = '-'
             else:
                 shortanchor = anchor
             pdict[name] = (fn2index[docname], typeindex, prio, shortanchor)
     return rv
예제 #5
0
 def get_objects(self, fn2index):
     rv = {}
     otypes = self._objtypes
     onames = self._objnames
     for domainname, domain in self.env.domains.iteritems():
         for fullname, dispname, type, docname, anchor, prio in \
                 domain.get_objects():
             # XXX use dispname?
             if docname not in fn2index:
                 continue
             if prio < 0:
                 continue
             # XXX splitting at dot is kind of Python specific
             prefix, name = rpartition(fullname, '.')
             pdict = rv.setdefault(prefix, {})
             try:
                 i = otypes[domainname, type]
             except KeyError:
                 i = len(otypes)
                 otypes[domainname, type] = i
                 otype = domain.object_types.get(type)
                 if otype:
                     # use unicode() to fire translation proxies
                     onames[i] = unicode(domain.get_type_name(otype))
                 else:
                     onames[i] = type
             pdict[name] = (fn2index[docname], i, prio)
     return rv
예제 #6
0
 def resolve_name(self, modname, parents, path, base):
     if modname is None:
         if path:
             mod_cls = path.rstrip('.')
         else:
             mod_cls = None
             # if documenting a class-level object without path,
             # there must be a current class, either from a parent
             # auto directive ...
             mod_cls = self.env.temp_data.get('autodoc:class')
             # ... or from a class directive
             if mod_cls is None:
                 mod_cls = self.env.temp_data.get('mat:class')
             # ... if still None, there's no way to know
             if mod_cls is None:
                 return None, []
         modname, cls = rpartition(mod_cls, '.')
         parents = [cls]
         # if the module name is still missing, get it like above
         if not modname:
             modname = self.env.temp_data.get('autodoc:module')
         if not modname:
             modname = self.env.temp_data.get('mat:module')
         # ... else, it stays None, which means invalid
     return modname, parents + [base]
예제 #7
0
 def resolve_name(self, modname, parents, path, base):
     if modname is None:
         if path:
             mod_cls = path.rstrip(".")
         else:
             mod_cls = None
             # if documenting a class-level object without path,
             # there must be a current class, either from a parent
             # auto directive ...
             if hasattr(self.env, "autodoc_current_class"):
                 mod_cls = self.env.autodoc_current_class
             # ... or from a class directive
             if mod_cls is None:
                 mod_cls = self.env.currclass
             # ... if still None, there's no way to know
             if mod_cls is None:
                 return None, []
         modname, cls = rpartition(mod_cls, ".")
         parents = [cls]
         # if the module name is still missing, get it like above
         if not modname and hasattr(self.env, "autodoc_current_module"):
             modname = self.env.autodoc_current_module
         if not modname:
             modname = self.env.currmodule
         # ... else, it stays None, which means invalid
     return modname, parents + [base]
예제 #8
0
 def resolve_name(self, modname, parents, path, base):
     if modname is None:
         if path:
             mod_cls = path.rstrip('.')
         else:
             mod_cls = None
             # if documenting a class-level object without path,
             # there must be a current class, either from a parent
             # auto directive ...
             mod_cls = self.env.temp_data.get('autodoc:class')
             # ... or from a class directive
             if mod_cls is None:
                 mod_cls = self.env.temp_data.get('mat:class')
             # ... if still None, there's no way to know
             if mod_cls is None:
                 return None, []
         modname, cls = rpartition(mod_cls, '.')
         parents = [cls]
         # if the module name is still missing, get it like above
         if not modname:
             modname = self.env.temp_data.get('autodoc:module')
         if not modname:
             modname = self.env.temp_data.get('mat:module')
         # ... else, it stays None, which means invalid
     return modname, parents + [base]
예제 #9
0
    def resolve_name(self, what, name):
        """
        Determine what module to import and what attribute to document.

        Returns a tuple of: the full name, the module name, a path of
        names to get via getattr, the signature and return annotation.
        """
        # first, parse the definition -- auto directives for classes and functions
        # can contain a signature which is then used instead of an autogenerated one
        try:
            path, base, args, retann = py_sig_re.match(name).groups()
        except:
            self.warn('invalid signature for auto%s (%r)' % (what, name))
            return
        # fullname is the fully qualified name, base the name after the last dot
        fullname = (path or '') + base

        if what == 'module':
            if args or retann:
                self.warn('ignoring signature arguments and return annotation '
                          'for automodule %s' % fullname)
            return fullname, fullname, [], None, None

        elif what in ('class', 'exception', 'function'):
            if path:
                mod = path.rstrip('.')
            else:
                mod = None
                # if documenting a toplevel object without explicit module, it can
                # be contained in another auto directive ...
                if hasattr(self.env, 'autodoc_current_module'):
                    mod = self.env.autodoc_current_module
                # ... or in the scope of a module directive
                if not mod:
                    mod = self.env.currmodule
            return fullname, mod, [base], args, retann

        else:
            if path:
                mod_cls = path.rstrip('.')
            else:
                mod_cls = None
                # if documenting a class-level object without path, there must be a
                # current class, either from a parent auto directive ...
                if hasattr(self.env, 'autodoc_current_class'):
                    mod_cls = self.env.autodoc_current_class
                # ... or from a class directive
                if mod_cls is None:
                    mod_cls = self.env.currclass
                # ... if still None, there's no way to know
                if mod_cls is None:
                    return fullname, None, [], args, retann
            mod, cls = rpartition(mod_cls, '.')
            # if the module name is still missing, get it like above
            if not mod and hasattr(self.env, 'autodoc_current_module'):
                mod = self.env.autodoc_current_module
            if not mod:
                mod = self.env.currmodule
            return fullname, mod, [cls, base], args, retann
예제 #10
0
파일: autodoc.py 프로젝트: wiless/IMTAphy
    def resolve_name(self, what, name):
        """
        Determine what module to import and what attribute to document.

        Returns a tuple of: the full name, the module name, a path of
        names to get via getattr, the signature and return annotation.
        """
        # first, parse the definition -- auto directives for classes and functions
        # can contain a signature which is then used instead of an autogenerated one
        try:
            path, base, args, retann = py_sig_re.match(name).groups()
        except:
            self.warn('invalid signature for auto%s (%r)' % (what, name))
            return
        # fullname is the fully qualified name, base the name after the last dot
        fullname = (path or '') + base

        if what == 'module':
            if args or retann:
                self.warn('ignoring signature arguments and return annotation '
                          'for automodule %s' % fullname)
            return fullname, fullname, [], None, None

        elif what in ('class', 'exception', 'function'):
            if path:
                mod = path.rstrip('.')
            else:
                mod = None
                # if documenting a toplevel object without explicit module, it can
                # be contained in another auto directive ...
                if hasattr(self.env, 'autodoc_current_module'):
                    mod = self.env.autodoc_current_module
                # ... or in the scope of a module directive
                if not mod:
                    mod = self.env.currmodule
            return fullname, mod, [base], args, retann

        else:
            if path:
                mod_cls = path.rstrip('.')
            else:
                mod_cls = None
                # if documenting a class-level object without path, there must be a
                # current class, either from a parent auto directive ...
                if hasattr(self.env, 'autodoc_current_class'):
                    mod_cls = self.env.autodoc_current_class
                # ... or from a class directive
                if mod_cls is None:
                    mod_cls = self.env.currclass
            mod, cls = rpartition(mod_cls, '.')
            # if the module name is still missing, get it like above
            if not mod and hasattr(self.env, 'autodoc_current_module'):
                mod = self.env.autodoc_current_module
            if not mod:
                mod = self.env.currmodule
            return fullname, mod, [cls, base], args, retann
예제 #11
0
 def get_descrefs(self, fn2index):
     rv = {}
     dt = self._desctypes
     for fullname, (doc, desctype) in self.env.descrefs.iteritems():
         prefix, name = rpartition(fullname, '.')
         pdict = rv.setdefault(prefix, {})
         try:
             i = dt[desctype]
         except KeyError:
             i = len(dt)
             dt[desctype] = i
         pdict[name] = (fn2index[doc], i)
     return rv
예제 #12
0
 def get_descrefs(self, fn2index):
     rv = {}
     dt = self._desctypes
     for fullname, (doc, desctype) in self.env.descrefs.iteritems():
         prefix, name = rpartition(fullname, ".")
         pdict = rv.setdefault(prefix, {})
         try:
             i = dt[desctype]
         except KeyError:
             i = len(dt)
             dt[desctype] = i
         pdict[name] = (fn2index[doc], i)
     return rv
예제 #13
0
 def get_objects(
     self, fn2index: Dict[str, int]
 ) -> Dict[str, Dict[str, Tuple[int, int, int, str]]]:
     rv = {}  # type: Dict[str, Dict[str, Tuple[int, int, int, str]]]
     otypes = self._objtypes
     onames = self._objnames
     for domainname, domain in sorted(self.env.domains.items()):
         for fullname, dispname, type, docname, anchor, prio in \
                 sorted(domain.get_objects()):
             if docname not in fn2index:
                 continue
             if prio < 0:
                 continue
             fullname = html.escape(fullname)
             dispname = html.escape(dispname)
             prefix, name = rpartition(dispname, '.')
             pdict = rv.setdefault(prefix, {})
             try:
                 typeindex = otypes[domainname, type]
             except KeyError:
                 typeindex = len(otypes)
                 otypes[domainname, type] = typeindex
                 otype = domain.object_types.get(type)
                 if otype:
                     # use str() to fire translation proxies
                     onames[typeindex] = (domainname, type,
                                          str(domain.get_type_name(otype)))
                 else:
                     onames[typeindex] = (domainname, type, type)
             if anchor == fullname:
                 shortanchor = ''
             elif anchor == type + '-' + fullname:
                 shortanchor = '-'
             else:
                 shortanchor = anchor
             pdict[name] = (fn2index[docname], typeindex, prio, shortanchor)
     return rv
예제 #14
0
 def get_objects(self, fn2index):
     # type: (Dict[str, int]) -> Dict[str, Dict[str, Tuple[int, int, int, str]]]
     rv = {}  # type: Dict[str, Dict[str, Tuple[int, int, int, str]]]
     otypes = self._objtypes
     onames = self._objnames
     for domainname, domain in sorted(self.env.domains.items()):
         for fullname, dispname, type, docname, anchor, prio in \
                 sorted(domain.get_objects()):
             if docname not in fn2index:
                 continue
             if prio < 0:
                 continue
             fullname = html.escape(fullname)
             dispname = html.escape(dispname)
             prefix, name = rpartition(dispname, '.')
             pdict = rv.setdefault(prefix, {})
             try:
                 typeindex = otypes[domainname, type]
             except KeyError:
                 typeindex = len(otypes)
                 otypes[domainname, type] = typeindex
                 otype = domain.object_types.get(type)
                 if otype:
                     # use str() to fire translation proxies
                     onames[typeindex] = (domainname, type,
                                          str(domain.get_type_name(otype)))
                 else:
                     onames[typeindex] = (domainname, type, type)
             if anchor == fullname:
                 shortanchor = ''
             elif anchor == type + '-' + fullname:
                 shortanchor = '-'
             else:
                 shortanchor = anchor
             pdict[name] = (fn2index[docname], typeindex, prio, shortanchor)
     return rv
예제 #15
0
파일: autodoc.py 프로젝트: lshmenor/IMTAphy
def generate_rst(what, name, members, options, add_content, document, lineno,
                 indent=u'', filename_set=None, check_module=False):
    env = document.settings.env

    result = None

    # first, parse the definition -- auto directives for classes and functions
    # can contain a signature which is then used instead of an autogenerated one
    try:
        path, base, signature, retann = py_sig_re.match(name).groups()
    except:
        warning = document.reporter.warning(
            'invalid signature for auto%s (%r)' % (what, name), line=lineno)
        return [warning], result
    # fullname is the fully qualified name, base the name after the last dot
    fullname = (path or '') + base
    # path is the name up to the last dot
    path = path and path.rstrip('.')

    warnings = []

    # determine what module to import -- mod is the module name, objpath the
    # path of names to get via getattr
    mod = None
    if what == 'module':
        mod = fullname
        if signature:
            warnings.append(document.reporter.warning(
                'ignoring arguments for automodule %s' % mod, line=lineno))
        objpath = []
    elif what in ('class', 'exception', 'function'):
        if path:
            mod = path
        else:
            # if documenting a toplevel object without explicit module, it can
            # be contained in another auto directive ...
            if hasattr(env, 'autodoc_current_module'):
                mod = env.autodoc_current_module
            # ... or in the scope of a module directive
            if not mod:
                mod = env.currmodule
        objpath = [base]
    else:
        if path:
            mod_cls = path
        else:
            # if documenting a class-level object without path, there must be a
            # current class, either from a parent auto directive ...
            if hasattr(env, 'autodoc_current_class'):
                mod_cls = env.autodoc_current_class
            # ... or from a class directive
            if not mod_cls:
                mod_cls = env.currclass
        mod, cls = rpartition(mod_cls, '.')
        # if the module name is still missing, get it like above
        if not mod and hasattr(env, 'autodoc_current_module'):
            mod = env.autodoc_current_module
        if not mod:
            mod = env.currmodule
        objpath = [cls, base]

    # by this time, a module *must* be determined
    if mod is None:
        warnings.append(document.reporter.warning(
            'don\'t know which module to import for autodocumenting %r '
            '(try placing a "module" or "currentmodule" directive in the document, '
            'or giving an explicit module name)' % fullname, line=lineno))
        return warnings, result

    # the name to put into the generated directive -- doesn't contain the module
    name_in_directive = '.'.join(objpath) or mod

    # now, import the module and get docstring(s) of object to document
    try:
        todoc = module = __import__(mod, None, None, ['foo'])
        if hasattr(module, '__file__') and module.__file__:
            modfile = module.__file__
            if modfile[-4:].lower() in ('.pyc', '.pyo'):
                modfile = modfile[:-1]
            if filename_set is not None:
                filename_set.add(modfile)
        else:
            modfile = None  # e.g. for builtin and C modules
        for part in objpath:
            todoc = getattr(todoc, part)
    except (ImportError, AttributeError):
        warnings.append(document.reporter.warning(
            'autodoc can\'t import/find %s %r, check your spelling '
            'and sys.path' % (what, str(fullname)), line=lineno))
        return warnings, result

    # check __module__ of object if wanted (for members not given explicitly)
    if check_module:
        if hasattr(todoc, '__module__'):
            if todoc.__module__ != mod:
                return warnings, result

    # format the object's signature, if any
    if signature is not None:
        # signature given explicitly -- the parentheses were stripped by the regex
        args = '(%s)' % signature
        if retann:
            args += retann
    else:
        try:
            args = format_signature(what, todoc)
        except Exception, err:
            warnings.append(document.reporter.warning(
                'error while formatting signature for %s: %s' %
                (fullname, err), line=lineno))
            args = ''
예제 #16
0
파일: autodoc.py 프로젝트: wiless/IMTAphy
def generate_rst(what,
                 name,
                 members,
                 options,
                 add_content,
                 document,
                 lineno,
                 indent=u'',
                 filename_set=None,
                 check_module=False):
    env = document.settings.env

    result = None

    # first, parse the definition -- auto directives for classes and functions
    # can contain a signature which is then used instead of an autogenerated one
    try:
        path, base, signature, retann = py_sig_re.match(name).groups()
    except:
        warning = document.reporter.warning(
            'invalid signature for auto%s (%r)' % (what, name), line=lineno)
        return [warning], result
    # fullname is the fully qualified name, base the name after the last dot
    fullname = (path or '') + base
    # path is the name up to the last dot
    path = path and path.rstrip('.')

    warnings = []

    # determine what module to import -- mod is the module name, objpath the
    # path of names to get via getattr
    mod = None
    if what == 'module':
        mod = fullname
        if signature:
            warnings.append(
                document.reporter.warning(
                    'ignoring arguments for automodule %s' % mod, line=lineno))
        objpath = []
    elif what in ('class', 'exception', 'function'):
        if path:
            mod = path
        else:
            # if documenting a toplevel object without explicit module, it can
            # be contained in another auto directive ...
            if hasattr(env, 'autodoc_current_module'):
                mod = env.autodoc_current_module
            # ... or in the scope of a module directive
            if not mod:
                mod = env.currmodule
        objpath = [base]
    else:
        if path:
            mod_cls = path
        else:
            # if documenting a class-level object without path, there must be a
            # current class, either from a parent auto directive ...
            if hasattr(env, 'autodoc_current_class'):
                mod_cls = env.autodoc_current_class
            # ... or from a class directive
            if not mod_cls:
                mod_cls = env.currclass
        mod, cls = rpartition(mod_cls, '.')
        # if the module name is still missing, get it like above
        if not mod and hasattr(env, 'autodoc_current_module'):
            mod = env.autodoc_current_module
        if not mod:
            mod = env.currmodule
        objpath = [cls, base]

    # by this time, a module *must* be determined
    if mod is None:
        warnings.append(
            document.reporter.warning(
                'don\'t know which module to import for autodocumenting %r '
                '(try placing a "module" or "currentmodule" directive in the document, '
                'or giving an explicit module name)' % fullname,
                line=lineno))
        return warnings, result

    # the name to put into the generated directive -- doesn't contain the module
    name_in_directive = '.'.join(objpath) or mod

    # now, import the module and get docstring(s) of object to document
    try:
        todoc = module = __import__(mod, None, None, ['foo'])
        if hasattr(module, '__file__') and module.__file__:
            modfile = module.__file__
            if modfile[-4:].lower() in ('.pyc', '.pyo'):
                modfile = modfile[:-1]
            if filename_set is not None:
                filename_set.add(modfile)
        else:
            modfile = None  # e.g. for builtin and C modules
        for part in objpath:
            todoc = getattr(todoc, part)
    except (ImportError, AttributeError):
        warnings.append(
            document.reporter.warning(
                'autodoc can\'t import/find %s %r, check your spelling '
                'and sys.path' % (what, str(fullname)),
                line=lineno))
        return warnings, result

    # check __module__ of object if wanted (for members not given explicitly)
    if check_module:
        if hasattr(todoc, '__module__'):
            if todoc.__module__ != mod:
                return warnings, result

    # format the object's signature, if any
    if signature is not None:
        # signature given explicitly -- the parentheses were stripped by the regex
        args = '(%s)' % signature
        if retann:
            args += retann
    else:
        try:
            args = format_signature(what, todoc)
        except Exception, err:
            warnings.append(
                document.reporter.warning(
                    'error while formatting signature for %s: %s' %
                    (fullname, err),
                    line=lineno))
            args = ''
예제 #17
0
파일: autodoc.py 프로젝트: lshmenor/IMTAphy
def generate_rst(what, name, members, undoc, add_content, document, lineno,
                 indent='', filename_set=None, check_module=False):
    env = document.settings.env

    # find out what to import
    if what == 'module':
        mod = obj = name
        objpath = []
    elif what in ('class', 'exception', 'function'):
        mod, obj = rpartition(name, '.')
        if not mod and hasattr(env, 'autodoc_current_module'):
            mod = env.autodoc_current_module
        if not mod:
            mod = env.currmodule
        objpath = [obj]
    else:
        mod_cls, obj = rpartition(name, '.')
        if not mod_cls and hasattr(env, 'autodoc_current_class'):
            mod_cls = env.autodoc_current_class
        if not mod_cls:
            mod_cls = env.currclass
        mod, cls = rpartition(mod_cls, '.')
        if not mod and hasattr(env, 'autodoc_current_module'):
            mod = env.autodoc_current_module
        if not mod:
            mod = env.currmodule
        objpath = [cls, obj]

    result = ViewList()

    if mod is None:
        warning = document.reporter.warning(
            'don\'t know which module to import for documenting %r '
            '(try placing a "module" or "currentmodule" directive in the document, '
            'or giving an explicit module name)' % name, line=lineno)
        return [warning], result

    try:
        todoc = module = __import__(mod, None, None, ['foo'])
        if filename_set is not None and hasattr(module, '__file__') and module.__file__:
            modfile = module.__file__
            if modfile.lower().endswith('.pyc') or modfile.lower().endswith('.pyo'):
                modfile = modfile[:-1]
            filename_set.add(modfile)
        for part in objpath:
            todoc = getattr(todoc, part)
        if check_module:
            # only checking __module__ for members not given explicitly
            if hasattr(todoc, '__module__'):
                if todoc.__module__ != mod:
                    return [], result
        docstring = todoc.__doc__
    except (ImportError, AttributeError):
        warning = document.reporter.warning(
            'autodoc can\'t import/find %s %r, check your spelling '
            'and sys.path' % (what, str(name)), line=lineno)
        return [warning], result

    # add directive header
    try:
        if what == 'class':
            args = inspect.formatargspec(*inspect.getargspec(todoc.__init__))
            if args[1:7] == 'self, ':
                args = '(' + args[7:]
            elif args == '(self)':
                args = '()'
        elif what in ('function', 'method'):
            args = inspect.formatargspec(*inspect.getargspec(todoc))
            if what == 'method':
                if args[1:7] == 'self, ':
                    args = '(' + args[7:]
                elif args == '(self)':
                    args = '()'
        else:
            args = ''
    except:
        args = ''
    if len(objpath) == 2:
        qualname = '%s.%s' % (cls, obj)
    else:
        qualname = obj
    result.append(indent + '.. %s:: %s%s' % (what, qualname, args), '<autodoc>')
    result.append('', '<autodoc>')

    # the module directive doesn't like content
    if what != 'module':
        indent += '   '

    # add docstring content
    if what == 'module' and env.config.automodule_skip_lines and docstring:
        docstring = '\n'.join(docstring.splitlines()
                              [env.config.automodule_skip_lines:])

    # get the encoding of the docstring
    module = getattr(todoc, '__module__', None)
    if module is not None and docstring is not None:
        docstring = docstring.decode(get_module_charset(module))

    docstring = prepare_docstring(docstring)
    for i, line in enumerate(docstring):
        result.append(indent + line, '<docstring of %s>' % name, i)

    # add source content, if present
    if add_content:
        for line, src in zip(add_content.data, add_content.items):
            result.append(indent + line, src[0], src[1])

    if not members or what in ('function', 'method', 'attribute'):
        return [], result

    env.autodoc_current_module = mod
    if objpath:
        env.autodoc_current_class = objpath[0]

    warnings = []
    # add members, if possible
    _all = members == ['__all__']
    members_check_module = False
    if _all:
        if what == 'module':
            # for implicit module members, check __module__ to avoid documenting
            # imported objects
            members_check_module = True
        all_members = sorted(inspect.getmembers(todoc))
    else:
        all_members = [(mname, getattr(todoc, mname)) for mname in members]
    for (membername, member) in all_members:
        if _all and membername.startswith('_'):
            continue
        doc = getattr(member, '__doc__', None)
        if not undoc and not doc:
            continue
        if what == 'module':
            if isinstance(member, types.FunctionType):
                memberwhat = 'function'
            elif isinstance(member, types.ClassType) or \
                 isinstance(member, type):
                if issubclass(member, base_exception):
                    memberwhat = 'exception'
                else:
                    memberwhat = 'class'
            else:
                # XXX: todo -- attribute docs
                continue
        else:
            if callable(member):
                memberwhat = 'method'
            elif isinstance(member, property):
                memberwhat = 'attribute'
            else:
                # XXX: todo -- attribute docs
                continue
        full_membername = name + '.' + membername
        subwarn, subres = generate_rst(memberwhat, full_membername, ['__all__'],
                                       undoc, None, document, lineno, indent,
                                       check_module=members_check_module)
        warnings.extend(subwarn)
        result.extend(subres)

    env.autodoc_current_module = None
    env.autodoc_current_class = None

    return warnings, result
예제 #18
0
파일: autodoc.py 프로젝트: wiless/IMTAphy
def generate_rst(what,
                 name,
                 members,
                 inherited,
                 undoc,
                 add_content,
                 document,
                 lineno,
                 indent='',
                 filename_set=None,
                 check_module=False):
    env = document.settings.env

    # find out what to import
    if what == 'module':
        mod = obj = name
        objpath = []
    elif what in ('class', 'exception', 'function'):
        mod, obj = rpartition(name, '.')
        if not mod and hasattr(env, 'autodoc_current_module'):
            mod = env.autodoc_current_module
        if not mod:
            mod = env.currmodule
        objpath = [obj]
    else:
        mod_cls, obj = rpartition(name, '.')
        if not mod_cls and hasattr(env, 'autodoc_current_class'):
            mod_cls = env.autodoc_current_class
        if not mod_cls:
            mod_cls = env.currclass
        mod, cls = rpartition(mod_cls, '.')
        if not mod and hasattr(env, 'autodoc_current_module'):
            mod = env.autodoc_current_module
        if not mod:
            mod = env.currmodule
        objpath = [cls, obj]

    result = ViewList()
    docstrings = []

    if mod is None:
        warning = document.reporter.warning(
            'don\'t know which module to import for documenting %r '
            '(try placing a "module" or "currentmodule" directive in the document, '
            'or giving an explicit module name)' % name,
            line=lineno)
        return [warning], result

    try:
        todoc = module = __import__(mod, None, None, ['foo'])
        if filename_set is not None and hasattr(
                module, '__file__') and module.__file__:
            modfile = module.__file__
            if modfile.lower().endswith('.pyc') or modfile.lower().endswith(
                    '.pyo'):
                modfile = modfile[:-1]
            filename_set.add(modfile)
        for part in objpath:
            todoc = getattr(todoc, part)
        if check_module:
            # only checking __module__ for members not given explicitly
            if hasattr(todoc, '__module__'):
                if todoc.__module__ != mod:
                    return [], result
        if getattr(todoc, '__doc__', None):
            docstrings.append(todoc.__doc__)
    except (ImportError, AttributeError):
        warning = document.reporter.warning(
            'autodoc can\'t import/find %s %r, check your spelling '
            'and sys.path' % (what, str(name)),
            line=lineno)
        return [warning], result

    # add directive header
    try:
        if what == 'class':
            args = inspect.formatargspec(*inspect.getargspec(todoc.__init__))
            if args[1:7] == 'self, ':
                args = '(' + args[7:]
            elif args == '(self)':
                args = '()'
        elif what in ('function', 'method'):
            args = inspect.formatargspec(*inspect.getargspec(todoc))
            if what == 'method':
                if args[1:7] == 'self, ':
                    args = '(' + args[7:]
                elif args == '(self)':
                    args = '()'
        else:
            args = ''
    except Exception:
        args = ''
    if len(objpath) == 2:
        qualname = '%s.%s' % (cls, obj)
    else:
        qualname = obj
    result.append(indent + '.. %s:: %s%s' % (what, qualname, args),
                  '<autodoc>')
    result.append('', '<autodoc>')

    # the module directive doesn't want content
    if what != 'module':
        indent += '   '

    # add docstring content
    if what == 'module' and env.config.automodule_skip_lines and docstrings[0]:
        docstrings[0] = '\n'.join(
            docstring.splitlines()[env.config.automodule_skip_lines:])

    # for classes, what the "docstring" is can be controlled via an option
    if what in ('class', 'exception'):
        content = env.config.autoclass_content
        if content in ('both', 'init'):
            initdocstring = getattr(todoc, '__init__', None).__doc__
            # for new-style classes, no __init__ means default __init__
            if initdocstring == object.__init__.__doc__:
                initdocstring = None
            if initdocstring:
                if content == 'init':
                    docstrings = [initdocstring]
                else:
                    docstrings.append('\n\n' + initdocstring)
        # the default is only the class docstring

    # get the encoding of the docstring
    module = getattr(todoc, '__module__', None)
    if module is not None:
        charset = get_module_charset(module)
        docstrings = [docstring.decode(charset) for docstring in docstrings]

    for docstring in docstrings:
        docstring = prepare_docstring(docstring)
        for i, line in enumerate(docstring):
            result.append(indent + line, '<docstring of %s>' % name, i)

    # add source content, if present
    if add_content:
        for line, src in zip(add_content.data, add_content.items):
            result.append(indent + line, src[0], src[1])

    if not members or what in ('function', 'method', 'attribute'):
        return [], result

    env.autodoc_current_module = mod
    if objpath:
        env.autodoc_current_class = objpath[0]

    warnings = []
    # add members, if possible
    _all = members == ['__all__']
    members_check_module = False
    if _all:
        if what == 'module':
            # for implicit module members, check __module__ to avoid documenting
            # imported objects
            members_check_module = True
            all_members = inspect.getmembers(todoc)
        else:
            if inherited:
                # getmembers() uses dir() which pulls in members from all base classes
                all_members = inspect.getmembers(todoc)
            else:
                # __dict__ contains only the members directly defined in the class
                all_members = sorted(todoc.__dict__.iteritems())
    else:
        all_members = [(mname, getattr(todoc, mname)) for mname in members]
    for (membername, member) in all_members:
        if _all and membername.startswith('_'):
            continue
        doc = getattr(member, '__doc__', None)
        if not undoc and not doc:
            continue
        if what == 'module':
            if isinstance(member, types.FunctionType):
                memberwhat = 'function'
            elif isinstance(member, types.ClassType) or \
                 isinstance(member, type):
                if issubclass(member, base_exception):
                    memberwhat = 'exception'
                else:
                    memberwhat = 'class'
            else:
                # XXX: todo -- attribute docs
                continue
        else:
            if callable(member):
                memberwhat = 'method'
            elif isdescriptor(member):
                memberwhat = 'attribute'
            else:
                # XXX: todo -- attribute docs
                continue
        full_membername = name + '.' + membername
        subwarn, subres = generate_rst(memberwhat,
                                       full_membername, ['__all__'],
                                       inherited,
                                       undoc,
                                       None,
                                       document,
                                       lineno,
                                       indent,
                                       check_module=members_check_module)
        warnings.extend(subwarn)
        result.extend(subres)

    env.autodoc_current_module = None
    env.autodoc_current_class = None

    return warnings, result