當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。