本文整理汇总了Python中sphinx.util.docstrings.prepare_docstring函数的典型用法代码示例。如果您正苦于以下问题:Python prepare_docstring函数的具体用法?Python prepare_docstring怎么用?Python prepare_docstring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了prepare_docstring函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_doc
def get_doc(self, encoding=None, ignore=1):
"""Overrides ClassDocumenter.get_doc to create the doc scraped from the Process object, then adds additional
content from the class docstring.
"""
from six import text_type
# Get the class docstring. This is a copy of the ClassDocumenter.get_doc method. Using "super" does weird stuff.
docstring = self.get_attr(self.object, '__doc__', None)
# make sure we have Unicode docstrings, then sanitize and split
# into lines
if isinstance(docstring, text_type):
docstring = prepare_docstring(docstring, ignore)
elif isinstance(docstring, str): # this will not trigger on Py3
docstring = prepare_docstring(force_decode(docstring, encoding), ignore)
# Create the docstring by scraping info from the Process instance.
pdocstrings = self.make_numpy_doc()
if self.options.docstring and docstring is not None:
# Add the sections from the class docstring itself.
pdocstrings.extend(docstring[self.options.skiplines:])
# Parse using the Numpy docstring format.
docstrings = NumpyDocstring(pdocstrings, self.env.config, self.env.app, what='class', obj=self.object,
options=self.options)
return [docstrings.lines()]
开发者ID:ldesousa,项目名称:PyWPS,代码行数:27,代码来源:ext_autodoc.py
示例2: make_rst
def make_rst(self):
module_name, class_name = self.arguments[:2]
obj = import_object(module_name, class_name)
events = [(event._func.__name__, opcode, format_args(event._func), prepare_docstring(event._func.__doc__)) for opcode, event in enumerate(obj.events)]
reqs = [(req._func.__name__, opcode, format_args(req._func), prepare_docstring(req._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:garyvdm,项目名称:pywayland,代码行数:15,代码来源:sphinx_wl_protocol.py
示例3: variable_reference
def variable_reference(v, st_type, in_type, default, doc, tier):
lines = [
v,
'-' * len(v),
'',
]
docstring = prepare_docstring(doc)
lines.extend([
docstring[0],
'',
])
lines.extend([
':Storage Type: ``%s``' % st_type.__name__,
':Input Type: ``%s``' % in_type.__name__,
':Default Value: %s' % default,
'',
])
lines.extend(docstring[1:])
lines.append('')
return lines
开发者ID:captainbrosset,项目名称:gecko-dev,代码行数:25,代码来源:sphinx.py
示例4: add_content
def add_content(self, more_content, no_docstring=False):
if not is_mpd_running():
return
try:
cls = self.object
instance = cls(must_start_worker = False, must_handle_state = False)
try:
#instance.initialize_code()
parameter_documentation = self.get_sphinx_doc_for_parameters(instance.parameters)
finally:
instance.stop()
except Exception as ex:
print ex
return
if self.analyzer:
# prevent encoding errors when the file name is non-ASCII
filename = unicode(self.analyzer.srcname,
sys.getfilesystemencoding(), 'replace')
sourcename = u'%s:docstring of %s' % (filename, self.fullname)
else:
sourcename = u'docstring of %s' % self.fullname
encoding = self.analyzer and self.analyzer.encoding
lines = prepare_docstring(force_decode(parameter_documentation, encoding))
for i, line in enumerate(self.process_doc([lines,])):
self.add_line(line, sourcename, i)
开发者ID:Ingwar,项目名称:amuse,代码行数:31,代码来源:autodoc_parameters.py
示例5: description
def description(f):
if f.__doc__ == None:
return ''
try:
return next(iter(prepare_docstring(f.__doc__)))
except StopIteration:
return ''
开发者ID:pombredanne,项目名称:horetu,代码行数:7,代码来源:options.py
示例6: get_doc
def get_doc(self, encoding=None):
content = self.env.config.autoclass_content
docstrings = []
attrdocstring = sage_getdoc_original(self.object)
if attrdocstring:
docstrings.append(attrdocstring)
# 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 = sage_getdoc_original(
self.get_attr(self.object, '__init__', None))
# 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)
doc = []
for docstring in docstrings:
if not isinstance(docstring, unicode):
docstring = force_decode(docstring, encoding)
doc.append(prepare_docstring(docstring))
return doc
开发者ID:aaditya-thakkar,项目名称:sage,代码行数:27,代码来源:sage_autodoc.py
示例7: make_rst
def make_rst(self):
app = import_object(self.arguments[0])
for method, path, endpoint in get_routes(app):
try:
blueprint, endpoint_internal = endpoint.split('.')
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, 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, path, docstring):
yield line
开发者ID:superduper,项目名称:sphinxcontrib-httpdomain,代码行数:35,代码来源:flask.py
示例8: function_reference
def function_reference(f, attr, args, doc):
lines = []
lines.extend([f, "-" * len(f), ""])
docstring = prepare_docstring(doc)
lines.extend([docstring[0], ""])
arg_types = []
for t in args:
if isinstance(t, list):
inner_types = [t2.__name__ for t2 in t]
arg_types.append(" | ".join(inner_types))
continue
arg_types.append(t.__name__)
arg_s = "(%s)" % ", ".join(arg_types)
lines.extend([":Arguments: %s" % arg_s, ""])
lines.extend(docstring[1:])
lines.append("")
return lines
开发者ID:ajkerrigan,项目名称:gecko-dev,代码行数:27,代码来源:sphinx.py
示例9: make_rst_for_method
def make_rst_for_method(self, path, method, http_method):
docstring = prepare_docstring((method.__doc__ or '').rstrip('\n'))
blank_line = docstring[-1]
docstring = docstring[:-1] # remove blank line appended automatically
funcdef = method._wsme_definition
# Add the parameter type information. Assumes that the
# developer has provided descriptions of the parameters.
for arg in funcdef.arguments:
docstring.append(':type %s: %s' %
(arg.name, datatypename(arg.datatype)))
# Add a blank line before return type to avoid the formatting issues
# that are caused because of missing blank lines between blocks
docstring.append(blank_line)
# Add the return type
if funcdef.return_type:
return_type = datatypename(funcdef.return_type)
docstring.append(':return type: %s' % return_type)
# restore the blank line added as a spacer
docstring.append(blank_line)
directive = http_directive(http_method, path, docstring)
return directive
开发者ID:CyrilRoelandteNovance,项目名称:sphinxcontrib-pecanwsme,代码行数:27,代码来源:rest.py
示例10: docs
def docs(f):
if f.__doc__ == None:
raise StopIteration
for line in prepare_docstring(f.__doc__):
m = re.match(r'^:param (?:[^:]+ )([^:]+): (.+)$', line)
if m:
yield m.groups()
开发者ID:pombredanne,项目名称:horetu,代码行数:7,代码来源:options.py
示例11: get_doc
def get_doc(self, encoding=None):
"""Decode and return lines of the docstring(s) for the object."""
docstring = self.get_attr(self.object, '__doc__', None)
if docstring:
# make sure we have Unicode docstrings, then sanitize and split
# into lines
return [prepare_docstring(force_decode(docstring, encoding))]
return []
开发者ID:hurtado452,项目名称:battleAtSea-master,代码行数:8,代码来源:autodoc.py
示例12: _rest2node
def _rest2node(self, rest, container=None):
vl = ViewList(prepare_docstring(rest))
if container is None:
node = nodes.container()
else:
node = container()
nested_parse_with_titles(self.state, vl, node)
return node
开发者ID:AnneGilles,项目名称:yafowil.documentation,代码行数:8,代码来源:sphinxext.py
示例13: fill_in_result
def fill_in_result(object_schema):
result["properties"] = {}
for property, propSchema in object_schema[u"properties"].iteritems():
attr = result["properties"][property] = {}
attr["title"] = propSchema["title"]
attr["description"] = prepare_docstring(propSchema["description"])
attr["required"] = property in object_schema.get("required", [])
attr["type"] = propSchema["type"]
开发者ID:zyegfryed,项目名称:flocker,代码行数:8,代码来源:publicapi.py
示例14: generate_docs
def generate_docs(self, clspath, more_content):
"""Generate documentation for this configman class"""
obj = import_class(clspath)
sourcename = 'docstring of %s' % clspath
# Add the header
modname, clsname = split_clspath(clspath)
self.add_line('.. %s:%s:: %s.%s' % ('py', 'class', modname, clsname), sourcename)
self.add_line('', sourcename)
# Add the docstring if there is one
docstring = getattr(obj, '__doc__', None)
if docstring:
docstringlines = prepare_docstring(docstring, ignore=1)
for i, line in enumerate(docstringlines):
self.add_line(' ' + line, sourcename, i)
self.add_line('', '')
# Add additional content from the directive if there was any
if more_content:
for line, src in zip(more_content.data, more_content.items):
self.add_line(' ' + line, src[0], src[1])
self.add_line('', '')
# Add configman related content
namespace = Namespace()
for cls in reversed(obj.__mro__):
try:
namespace.update(cls.required_config)
except AttributeError:
pass
if namespace:
self.add_line(' Configuration:', '')
self.add_line('', '')
sourcename = 'class definition'
def generate_namespace_docs(namespace, basename=''):
for name, value in namespace.iteritems():
if isinstance(value, Namespace):
generate_namespace_docs(value, name + '_')
elif isinstance(value, Option):
self.add_line(' ``%s``' % (basename + value.name), sourcename)
self.add_line(' :default: ``%r``' % value.default, sourcename)
self.add_line(' :converter: %r' % value.from_string_converter, sourcename)
if value.reference_value_from:
self.add_line(' :base: ``%s``' % (value.reference_value_from + '.' + value.name), sourcename)
self.add_line('', '')
self.add_line(' %s' % value.doc, sourcename)
self.add_line('', '')
elif isinstance(value, Aggregation):
# Ignore aggregations--they're for setting something up
# using a bunch of configuratino things (I think)
pass
else:
raise Exception('No idea what to do with %r' % value)
generate_namespace_docs(namespace)
开发者ID:yangluphil,项目名称:socorro-collector,代码行数:58,代码来源:configmandoc.py
示例15: add_docstring
def add_docstring(docstring):
if docstring:
with IndentBlock(self):
self.add_line(u'', directive_name)
source_name = u'docstring of %s.%s' % (self.fullname, name)
docstring = [prepare_docstring(force_decode(docstring, None))]
for i, line in enumerate(self.process_doc(docstring)):
self.add_line(line, source_name, i)
self.add_line(u'', directive_name)
开发者ID:infrae,项目名称:sphinxcontrib.infrae,代码行数:9,代码来源:autointerface.py
示例16: _introspectRoute
def _introspectRoute(route, exampleByIdentifier, schema_store):
"""
Given a L{KleinRoute}, extract the information to generate documentation.
@param route: Route to inspect
@type route: L{KleinRoute}
@param exampleByIdentifier: A one-argument callable that accepts an example
identifier and returns an HTTP session example.
@param dict schema_store: A mapping between schema paths
(e.g. ``b/v1/types.json``) and the JSON schema structure.
@return: Information about the route
@rtype: L{dict} with the following keys.
- C{'description'}:
L{list} of L{str} containing a prose description of the endpoint.
- C{'input'} I{(optional)}:
L{dict} describing the input schema. Has C{'properties'} key with
a L{list} of L{dict} of L{dict} with keys C{'title'},
C{'description'} and C{'required'} describing the toplevel
properties of the schema.
- C{'input_schema'} I{(optional)}:
L{dict} including the verbatim input JSON Schema.
- C{'output'} I{(optional)}:
see C{'input'}.
- C{'output_schema'} I{(optional)}:
L{dict} including the verbatim output JSON Schema.
- C{'paged'} I{(optional)}:
If present, the endpoint is paged.
L{dict} with keys C{'defaultKey'} and C{'otherKeys'} giving the
names of default and available sort keys.
- C{'examples'}:
A list of examples (L{Example} instances) for this endpoint.
"""
result = {}
userDocumentation = route.attributes.get(
"userDocumentation", "Undocumented.")
result['description'] = prepare_docstring(userDocumentation)
inputSchema = route.attributes.get('inputSchema', None)
outputSchema = route.attributes.get('outputSchema', None)
if inputSchema:
result['input'] = _parseSchema(inputSchema, schema_store)
result["input_schema"] = inputSchema
if outputSchema:
result['output'] = _parseSchema(outputSchema, schema_store)
result["output_schema"] = outputSchema
examples = route.attributes.get("examples") or []
result['examples'] = list(
Example.fromDictionary(exampleByIdentifier(identifier))
for identifier in examples)
return result
开发者ID:ALSEDLAH,项目名称:flocker,代码行数:57,代码来源:publicapi.py
示例17: fill_in_result
def fill_in_result(object_schema):
result['properties'] = {}
for property, propSchema in object_schema[u'properties'].iteritems():
attr = result['properties'][property] = {}
attr['title'] = propSchema['title']
attr['description'] = prepare_docstring(
propSchema['description'])
attr['required'] = property in object_schema.get("required", [])
attr['type'] = propSchema['type']
开发者ID:ALSEDLAH,项目名称:flocker,代码行数:9,代码来源:publicapi.py
示例18: test_prepare_docstring
def test_prepare_docstring():
docstring = """multiline docstring
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua::
Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
"""
assert (prepare_docstring(docstring) ==
["multiline docstring",
"",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit,",
"sed do eiusmod tempor incididunt ut labore et dolore magna",
"aliqua::",
"",
" Ut enim ad minim veniam, quis nostrud exercitation",
" ullamco laboris nisi ut aliquip ex ea commodo consequat.",
""])
assert (prepare_docstring(docstring, 5) ==
["multiline docstring",
"",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit,",
"sed do eiusmod tempor incididunt ut labore et dolore magna",
"aliqua::",
"",
"Ut enim ad minim veniam, quis nostrud exercitation",
" ullamco laboris nisi ut aliquip ex ea commodo consequat.",
""])
docstring = """
multiline docstring with leading empty lines
"""
assert (prepare_docstring(docstring) ==
["multiline docstring with leading empty lines",
""])
docstring = "single line docstring"
assert (prepare_docstring(docstring) ==
["single line docstring",
""])
开发者ID:AWhetter,项目名称:sphinx,代码行数:44,代码来源:test_util_docstrings.py
示例19: document_members
def document_members(self, all_members=True):
oldindent = self.indent
members = list(self.object.attributes.items())
if self.options.members is not autodoc.ALL:
specified = []
for line in (self.options.members or []):
specified.extend(line.split())
members = {
name: value for name, value in members if name in specified
}
member_order = (
self.options.member_order or self.env.config.autodoc_member_order
)
if member_order == 'alphabetical':
members.sort()
if member_order == 'groupwise':
members.sort(key=lambda e: isinstance(e[1], Method))
elif member_order == 'bysource' and self.analyzer:
name = self.object.__name__
def keyfunc(entry):
return self.analyzer.tagorder.get(
'.'.join((name, entry[0])),
len(self.analyzer.tagorder)
)
members.sort(key=keyfunc)
for name, specification in members:
self.add_line(u'', '<autointerface>')
if isinstance(specification, Method):
self.add_line(
u'.. method:: {name}{arguments}'.format(
name=name,
arguments=inspect.formatargspec(
*specification.argument_specification
)
),
'<autointerface>'
)
else:
self.add_line(
u'.. attribute:: {name}'.format(name=name),
'<autointerface>'
)
doc = specification.docstring
if doc:
self.add_line(u'', '<autointerface>')
self.indent += self.content_indent
sourcename = u'docstring of %s.%s' % (self.fullname, name)
docstrings = [prepare_docstring(force_decode(doc, None))]
for i, line in enumerate(self.process_doc(docstrings)):
self.add_line(line, sourcename, i)
self.add_line(u'', '<autointerface>')
self.indent = oldindent
开发者ID:msiedlarek,项目名称:wiring,代码行数:56,代码来源:sphinx_wiring.py
示例20: format_docstring
def format_docstring(docstring):
"""Format the docstring to make it well-readable.
:param docstring: string.
:returns: formatted string.
"""
if docstring:
return "\n".join(docstrings.prepare_docstring(docstring))
else:
return ""
开发者ID:danielmellado,项目名称:rally,代码行数:10,代码来源:utils.py
注:本文中的sphinx.util.docstrings.prepare_docstring函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论