docs.py 文件源码

python
阅读 26 收藏 0 点赞 0 评论 0

项目:cleaREST 作者: petr-s 项目源码 文件源码
def parse(doc_string):  # TODO: rewrite (really ugly)
    if not doc_string:
        return {}

    def _paragraph(node_):
        return str(node_.children[0])

    def _is_node(node_, name):
        return node_ and node_.tagname == name

    def _is_paragraph(node_, value):
        return _is_node(node_, "paragraph") and _paragraph(node_) == value

    def _fields(node_):
        fields = []
        returns = None
        for field in node_:
            name, body = None, None
            for child in field:
                if _is_node(child, "field_name"):
                    name = str(child.children[0])
                elif _is_node(child, "field_body"):
                    body = _paragraph(child.children[0])
            name_pieces = name.split(" ")
            if len(name_pieces) == 3:
                fields.append(Parameter(name_pieces[2], name_pieces[1], body))
            elif len(name_pieces) == 2:
                fields.append(Parameter(name_pieces[1], None, body))
            elif name_pieces[0] == "return":
                returns = body
        return fields, returns

    result = {}
    text = []
    root = publish_doctree(doc_string).children[0]
    if len(root.children) == 1 and root.children[0].tagname == "#text":
        text.append(_paragraph(root))
    else:
        for index, (node, next_node) in enumerate(zip(root.children, root.children[1:] + [None])):
            if index == 0 and _is_node(node, "paragraph"):
                text.append(str(node.children[0]))
            else:
                if _is_node(next_node, "literal_block") and _is_paragraph(node, ":example:"):
                    result["example"] = str(next_node.children[0])
                elif _is_node(next_node, "literal_block") and _is_paragraph(node, ":rexample:"):
                    result["result_example"] = str(next_node.children[0])
                elif _is_node(node, "field_list"):
                    result["params"], result["return"] = _fields(node)
    result["text"] = "".join(text)
    return result
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号