我可以在Sphinx文档中抑制变量扩展吗?

时间:2014-01-22 15:46:17

标签: python variables documentation python-sphinx

在我的代码中我有

X_DEFAULT = ['a', 'long', 'list', 'of', 'values', 'that', 'is', 'really', 'ugly', 'to', 'see', 'over', 'and', 'over', 'again', 'every', 'time', 'it', 'is', 'referred', 'to', 'in', 'the', 'documentation']

以后

def some_function(..., x=X_DEFAULT, ...):

所以在我的Sphinx文档中,使用(例如,使用.. autofunction::等),我在X_DEFAULT的签名中扩展了some_function的整个长而笨重的值:< / p>

  

some_function ...,x = ['a','long','list','of','values','that',   '是','真的','丑','到','看','过','和','过','再次',   '每个','时间','它','是','引用','到','在',''',   '文档'],...

是否有办法在生成的文档中禁止此替换,最好使用返回X_DEFAULT定义的链接:

  

some_function ...,x = X_DEFAULT,...


我知道我可以手动覆盖我明确列为Sphinx文档指令参数的每个函数和方法的签名,但这不是我的目标。我也知道我可以使用autodoc_docstring_signature和docstring的第一行,但这会产生错误的文档字符串,真正用于内省失败的情况(如C)。我怀疑在autodoc-process-signature中我可以做些什么可能足够(但并不完美),但我不确定如何继续。

1 个答案:

答案 0 :(得分:0)

一种方法,例如,将“在模块级别定义的所有值”的“替换”替换为“公共常量”(由没有前导下划线的全部大写字母识别),其唯一名称可以可以在定义它的模块中找到:

def pretty_signature(app, what, name, obj, options, signature, return_annotation):
    if what not in ('function', 'method', 'class'):
        return

    if signature is None:
        return

    import inspect
    mod = inspect.getmodule(obj)

    new_sig = signature
    # Get all-caps names with no leading underscore
    global_names = [name for name in dir(mod) if name.isupper() if name[0] != '_']
    # Get only names of variables with distinct values
    names_to_replace = [name for name in global_names
                        if [mod.__dict__[n] for n in global_names].count(mod.__dict__[name]) == 1]
    # Substitute name for value in signature, including quotes in a string value
    for var_name in names_to_replace:
        var_value = mod.__dict__[var_name]
        value_string = str(var_value) if type(var_value) is not str else "'{0}'".format(var_value)
        new_sig = new_sig.replace(value_string, var_name)

    return new_sig, return_annotation

def setup(app):
    app.connect('autodoc-process-signature', pretty_signature)

另一种方法是直接从源代码中获取docstring:

import inspect
import re

def pretty_signature(app, what, name, obj, options, signature, return_annotation):
    """Prevent substitution of values for names in signatures by preserving source text."""
    if what not in ('function', 'method', 'class') or signature is None:
        return

    new_sig = signature
    if inspect.isfunction(obj) or inspect.isclass(obj) or inspect.ismethod(obj):
        sig_obj = obj if not inspect.isclass(obj) else obj.__init__
        sig_re = '\((self|cls)?,?\s*(.*?)\)\:'
        new_sig = ' '.join(re.search(sig_re, inspect.getsource(sig_obj), re.S).group(2).replace('\n', '').split())
        new_sig = '(' + new_sig + ')'

    return new_sig, return_annotation