当前位置: 首页>>代码示例>>Python>>正文


Python docstrings.prepare_docstring方法代码示例

本文整理汇总了Python中sphinx.util.docstrings.prepare_docstring方法的典型用法代码示例。如果您正苦于以下问题:Python docstrings.prepare_docstring方法的具体用法?Python docstrings.prepare_docstring怎么用?Python docstrings.prepare_docstring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sphinx.util.docstrings的用法示例。


在下文中一共展示了docstrings.prepare_docstring方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_doc

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def get_doc(self, encoding=None, ignore=1):
        lines = getattr(self, '_new_docstrings', None)
        if lines is not None:
            return lines

        doc = super(AnyBlokDeclarationDocumenter, self).get_doc(
            encoding=encoding, ignore=ignore)

        registry_name = self.get_attr(self.object, '__registry_name__', None)
        declaration = self.get_attr(self.object, '__declaration__', None)
        if registry_name and declaration:
            autodoc = self.get_attr(declaration, 'autodoc_class', None)
            if autodoc is not None:
                docstrings = autodoc(self.object)
            else:
                docstrings = autodoc_registration(declaration, self.object)
                if getattr(declaration, 'autodoc_anyblok_fields', False):
                    docstrings += autodoc_fields(declaration, self.object)
            if docstrings:
                doc.append(prepare_docstring(docstrings, ignore))

        return doc 
开发者ID:AnyBlok,项目名称:AnyBlok,代码行数:24,代码来源:blok.py

示例2: make_rst

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def make_rst(self):
        app = import_object(self.arguments[0])
        for method, path, target in get_routes(app):
            endpoint = target.name or target.callback.__name__
            if self.endpoints and endpoint not in self.endpoints:
                continue
            if endpoint in self.undoc_endpoints:
                continue
            view = target.callback
            docstring = view.__doc__ or ''
            if not isinstance(docstring, six.text_type):
                analyzer = ModuleAnalyzer.for_module(view.__module__)
                docstring = force_decode(docstring, analyzer.encoding)
            if not docstring and 'include-empty-docstring' not in self.options:
                continue
            docstring = prepare_docstring(docstring)
            for line in http_directive(method, path, docstring):
                yield line 
开发者ID:preems,项目名称:nltk-server,代码行数:20,代码来源:bottle.py

示例3: make_rst

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def make_rst(self):
        app = import_object(self.arguments[0])
        for method, path, handler in get_routes(app):
            class_name = handler.__name__
            method_name = getattr(handler, method).__name__
            endpoint = '.'.join((class_name, method_name))

            if self.endpoints and endpoint not in self.endpoints:
                continue
            if endpoint in self.undoc_endpoints:
                continue

            docstring = getattr(handler, method).__doc__ or ''
            #if not isinstance(docstring, unicode):
            #    analyzer = ModuleAnalyzer.for_module(view.__module__)
            #    docstring = force_decode(docstring, analyzer.encoding)
            if not docstring and 'include-empty-docstring' not in self.options:
                continue
            docstring = prepare_docstring(docstring)
            for line in http_directive(method, normalize_path(path), docstring):
                yield line 
开发者ID:preems,项目名称:nltk-server,代码行数:23,代码来源:tornado.py

示例4: make_rst

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def make_rst(self):
        module_name, class_name = self.arguments[:2]
        obj = import_object(module_name, class_name)
        events = [
            (event.py_func.__name__, opcode, format_args(event.py_func), prepare_docstring(event.py_func.__doc__))
            for opcode, event in enumerate(obj.events)
        ]
        reqs = [(req.py_func.__name__, opcode, format_args(req.py_func),
                 prepare_docstring(req.py_func.__doc__)) for opcode, req in enumerate(obj.requests)]
        context = {
            'module': module_name,
            'class_name': class_name,
            'obj': obj,
            'events': events,
            'requests': reqs
        }
        rst = wl_protocol_template.render(**context)
        for line in rst.splitlines():
            yield line 
开发者ID:flacjacket,项目名称:pywayland,代码行数:21,代码来源:sphinx_wl_protocol.py

示例5: get_doc

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def get_doc(self, encoding=None):
        content = self.env.config.autoclass_content

        docstrings = []
        docstring = self.get_attr(self.object, '__doc__', None)
        if docstring:
            docstrings.append(docstring)

        # for classes, what the "docstring" is can be controlled via a
        # config value; the default is only the class docstring
        if content in ('both', 'init'):
            initdocstring = self.get_attr(
                self.get_attr(self.object, '__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(initdocstring)

        return [prepare_docstring(force_decode(docstring, encoding))
                for docstring in docstrings] 
开发者ID:cihologramas,项目名称:pyoptools,代码行数:26,代码来源:sage_autodoc.py

示例6: make_rst

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def make_rst(self):
        app = import_object(self.arguments[0])
        for method, path, endpoint in get_routes(app):
            try:
                blueprint, _, endpoint_internal = endpoint.rpartition('.')
                if self.blueprints and blueprint not in self.blueprints:
                    continue
                if blueprint in self.undoc_blueprints:
                    continue
            except ValueError:
                pass  # endpoint is not within a blueprint

            if self.endpoints and endpoint not in self.endpoints:
                continue
            if endpoint in self.undoc_endpoints:
                continue
            try:
                static_url_path = app.static_url_path # Flask 0.7 or higher
            except AttributeError:
                static_url_path = app.static_path # Flask 0.6 or under
            if ('undoc-static' in self.options and endpoint == 'static' and
                path == static_url_path + '/(path:filename)'):
                continue
            view = app.view_functions[endpoint]
            docstring = view.__doc__ or ''
            if hasattr(view, 'view_class'):
                meth_func = getattr(view.view_class, method.lower(), None)
                if meth_func and meth_func.__doc__:
                    docstring = meth_func.__doc__
            if not isinstance(docstring, six.text_type):
                analyzer = ModuleAnalyzer.for_module(view.__module__)
                docstring = force_decode(docstring, analyzer.encoding)
    
            if not docstring and 'include-empty-docstring' not in self.options:
                continue
            docstring = prepare_docstring(docstring)
            for line in http_directive(method, path, docstring):
                yield line 
开发者ID:preems,项目名称:nltk-server,代码行数:40,代码来源:flask.py

示例7: autodoc_process_docstring

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def autodoc_process_docstring(app, what, name, obj, options, lines):
    """Handler for the event emitted when autodoc processes a docstring.
    See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.

    The TL;DR is that we can modify ``lines`` in-place to influence the output.
    """
    # check that only symbols that can be directly imported from ``callee``
    # package are being documented
    _, symbol = name.rsplit('.', 1)
    if symbol not in callee.__all__:
        raise SphinxError(
            "autodoc'd '%s' is not a part of the public API!" % name)

    # for classes exempt from automatic merging of class & __init__ docs,
    # pretend their __init__ methods have no docstring at all,
    # so that nothing will be appended to the class's docstring
    if what == 'class' and name in autoclass_content_exceptions:
        # amusingly, when autodoc reads the constructor's docstring
        # for appending it to class docstring, it will report ``what``
        # as 'class' (again!); hence we must check what it actually read
        ctor_docstring_lines = prepare_docstring(obj.__init__.__doc__)
        if lines == ctor_docstring_lines:
            lines[:] = []


# -- Options for intersphinx extension ------------------------------------ 
开发者ID:Xion,项目名称:callee,代码行数:28,代码来源:conf.py

示例8: make_rst

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def make_rst(self, section_title_set):
        # print('importing falcon app %s...' % self.arguments[0])
        app = autohttp_import_object(self.arguments[0])
        for method, path, handler in get_routes(app):
            docstring = handler.__doc__
            if not isinstance(docstring, str):
                analyzer = ModuleAnalyzer.for_module(handler.__module__)
                docstring = force_decode(docstring, analyzer.encoding)
            if not docstring and 'include-empty-docstring' not in self.options:
                continue
            # exclude falcon HTTPMethodNotAllowed endpoints
            if docstring == 'Raise 405 HTTPMethodNotAllowed error':
                continue
            if not docstring:
                continue
            if hasattr(handler, '__self__'):
                if not (handler.__self__.allow_read_no_auth and method == 'GET'):
                    docstring += '\n:reqheader Authorization: see :ref:`hmac-auth-label`.\n'

            docstring = prepare_docstring(docstring)

            # generate section title if needed
            if path.startswith('/v'):
                section_title = '/'.join(path.split('/')[0:3])
            else:
                section_title = path
            if section_title not in section_title_set:
                section_title_set.add(section_title)
                yield section_title
                yield '_' * len(section_title)

            for line in autohttp_http_directive(method, path, docstring):
                yield line 
开发者ID:linkedin,项目名称:iris,代码行数:35,代码来源:sphinx_extension.py

示例9: make_rst

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def make_rst(self, section_title_set):
        # print('importing falcon app %s...' % self.arguments[0])
        app = autohttp_import_object(self.arguments[0])
        for method, path, handler in get_routes(app):
            docstring = handler.__doc__
            if not isinstance(docstring, str):
                analyzer = ModuleAnalyzer.for_module(handler.__module__)
                docstring = force_decode(docstring, analyzer.encoding)
            if not docstring and 'include-empty-docstring' not in self.options:
                continue
            if not docstring:
                continue
            docstring = prepare_docstring(docstring)

            # generate section title if needed
            if path.startswith('/api'):
                section_title = '/'.join(path.split('/')[0:4])
            else:
                section_title = path
            if section_title not in section_title_set:
                section_title_set.add(section_title)
                yield section_title
                yield '_' * len(section_title)

            for line in autohttp_http_directive(method, path, docstring):
                yield line 
开发者ID:linkedin,项目名称:oncall,代码行数:28,代码来源:sphinx_extension.py

示例10: get_doc

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def get_doc(self, encoding: str = None, ignore: int = 1) -> List[List[str]]:
        """Decode and return lines of the docstring(s) for the object."""
        if encoding is not None:
            warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
                          % self.__class__.__name__,
                          RemovedInSphinx40Warning)
        docstring = getdoc(self.object, self.get_attr,
                           self.env.config.autodoc_inherit_docstrings)
        if docstring:
            tab_width = self.directive.state.document.settings.tab_width
            return [prepare_docstring(docstring, ignore, tab_width)]
        return [] 
开发者ID:thu-coai,项目名称:cotk,代码行数:14,代码来源:__init__.py

示例11: _find_signature

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def _find_signature(self, encoding: str = None) -> Tuple[str, str]:
        if encoding is not None:
            warnings.warn("The 'encoding' argument to autodoc.%s._find_signature() is "
                          "deprecated." % self.__class__.__name__,
                          RemovedInSphinx40Warning)
        docstrings = self.get_doc()
        self._new_docstrings = docstrings[:]
        result = None
        for i, doclines in enumerate(docstrings):
            # no lines in docstring, no match
            if not doclines:
                continue
            # match first line of docstring against signature RE
            match = py_ext_sig_re.match(doclines[0])
            if not match:
                continue
            exmod, path, base, args, retann = match.groups()
            # the base name must match ours
            valid_names = [self.objpath[-1]]  # type: ignore
            if isinstance(self, ClassDocumenter):
                valid_names.append('__init__')
                if hasattr(self.object, '__mro__'):
                    valid_names.extend(cls.__name__ for cls in self.object.__mro__)
            if base not in valid_names:
                continue
            # re-prepare docstring to ignore more leading indentation
            tab_width = self.directive.state.document.settings.tab_width  # type: ignore
            self._new_docstrings[i] = prepare_docstring('\n'.join(doclines[1:]),
                                                        tabsize=tab_width)
            result = args, retann
            # don't look any further
            break
        return result 
开发者ID:thu-coai,项目名称:cotk,代码行数:35,代码来源:__init__.py

示例12: _parseSchema

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def _parseSchema(schema, schema_store):
    """
    Parse a JSON Schema and return some information to document it.

    This supports only two kinds of schemas: objects, and arrays of a
    single kind of object. If your schema is more complex you may need to
    expand this code to address that.

    See:
     * https://clusterhq.atlassian.net/browse/FLOC-1697
     * https://clusterhq.atlassian.net/browse/FLOC-1698

    @param schema: L{dict} representing a JSON Schema.

    @param dict schema_store: A mapping between schema paths
        (e.g. ``b/v1/types.json``) and the JSON schema structure.

    @return: A L{dict} representing the information needed to
        document the schema.
    """
    result = {}
    schema = resolveSchema(schema, schema_store)

    def fill_in_result(object_schema):
        result['properties'] = {}
        for prop, propSchema in object_schema[u'properties'].iteritems():
            attr = result['properties'][prop] = {}
            attr['title'] = propSchema['title']
            attr['description'] = prepare_docstring(
                propSchema['description'])
            attr['required'] = prop in object_schema.get("required", [])
            attr['type'] = propSchema['type']

    if schema[u"type"] == u"object":
        result["type"] = "object"
        fill_in_result(schema)
    elif schema[u"type"] == u"array":
        result["type"] = "array"
        child_schema = schema[u"items"]
        if child_schema.get("type") == "object":
            fill_in_result(child_schema)
        else:
            raise Exception("Only single object type allowed in an array.")
    else:
        raise Exception(
            'Non-object/array top-level definitions not supported.')

    return result 
开发者ID:ClusterHQ,项目名称:flocker,代码行数:50,代码来源:publicapi.py

示例13: parse_docstring

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def parse_docstring(docstring):
    """Parse the docstring into its components.

    :returns: a dictionary of form
              {
                  "short_description": ...,
                  "long_description": ...,
                  "params": [{"name": ..., "doc": ...}, ...],
                  "returns": ...
              }
    """

    short_description = long_description = returns = ""
    params = []

    if docstring:
        docstring = "\n".join(docstrings.prepare_docstring(docstring))

        lines = docstring.split("\n", 1)
        short_description = lines[0]

        if len(lines) > 1:
            long_description = lines[1].strip()

            params_returns_desc = None

            match = PARAM_OR_RETURNS_REGEX.search(long_description)
            if match:
                long_desc_end = match.start()
                params_returns_desc = long_description[long_desc_end:].strip()
                long_description = long_description[:long_desc_end].rstrip()

            if params_returns_desc:
                params = [
                    {"name": name,
                     "doc": "\n".join(docstrings.prepare_docstring(doc))}
                    for name, doc in PARAM_REGEX.findall(params_returns_desc)
                ]

                match = RETURNS_REGEX.search(params_returns_desc)
                if match:
                    returns = reindent(match.group("doc"))

    return {
        "short_description": short_description,
        "long_description": long_description,
        "params": params,
        "returns": returns
    } 
开发者ID:GeosoftInc,项目名称:gxpy,代码行数:51,代码来源:docstring_info.py

示例14: make_rst

# 需要导入模块: from sphinx.util import docstrings [as 别名]
# 或者: from sphinx.util.docstrings import prepare_docstring [as 别名]
def make_rst(self):
        app = import_object(self.arguments[0])
        if self.endpoints:
            routes = itertools.chain(*[get_routes(app, endpoint)
                                     for endpoint in self.endpoints])
        else:
            routes = get_routes(app)

        for method, paths, endpoint in routes:
            if not self.check_regex_validate_path(paths):
                continue
            if self.check_regex_cancel_path(paths):
                continue
            try:
                blueprint, _, endpoint_internal = endpoint.rpartition('.')
                if self.blueprints and blueprint not in self.blueprints:
                    continue
                if blueprint in self.undoc_blueprints:
                    continue
            except ValueError:
                pass  # endpoint is not within a blueprint

            if endpoint in self.undoc_endpoints:
                continue
            try:
                static_url_path = app.static_url_path  # Flask 0.7 or higher
            except AttributeError:
                static_url_path = app.static_path  # Flask 0.6 or under
            if ('undoc-static' in self.options and endpoint == 'static' and
                    static_url_path + '/(path:filename)' in paths):
                continue
            view = app.view_functions[endpoint]
            docstring = view.__doc__ or ''
            if hasattr(view, 'view_class'):
                meth_func = getattr(view.view_class, method.lower(), None)
                if meth_func and meth_func.__doc__:
                    docstring = meth_func.__doc__
            if not isinstance(docstring, six.text_type):
                analyzer = ModuleAnalyzer.for_module(view.__module__)
                docstring = force_decode(docstring, analyzer.encoding)

            if not docstring and 'include-empty-docstring' not in self.options:
                continue
            docstring = prepare_docstring(docstring)
            for line in http_directive(method, paths, docstring):
                yield line 
开发者ID:ovh,项目名称:ip-reputation-monitoring,代码行数:48,代码来源:extended_autohttp_flask.py


注:本文中的sphinx.util.docstrings.prepare_docstring方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。