【问题标题】:Is it possible to hide Python function arguments in Sphinx?是否可以在 Sphinx 中隐藏 Python 函数参数?
【发布时间】:2015-05-30 05:23:22
【问题描述】:

假设我有Numpydoc style 中记录的以下函数,并且该文档是使用Sphinx autofunction directive 自动生成的:

def foo(x, y, _hidden_argument=None):
    """
    Foo a bar.

    Parameters
    ----------
    x: str
        The first argument to foo.
    y: str
        The second argument to foo.

    Returns
    -------
    The barred foo.

    """
    if _hidden_argument:
        _end_users_shouldnt_call_this_function(x, y)
    return x + y

我不想将隐藏参数宣传为我的公共 API 的一部分,但它会显示在我的自动生成的文档中。有什么方法可以告诉 Sphinx 忽略函数的特定参数,或者(甚至更好)使其自动忽略带前导下划线的参数?

【问题讨论】:

  • 你所拥有的似乎真的很糟糕的设计。相反,您应该有一个 _foo 函数,其中 _hidden_parameter 根本没有隐藏,尽管文档警告不要使用 _foo 函数,然后是 foo only两个参数简单地用正确的值调用_foo。当你需要最后一个参数时,你使用_foo,当你不需要它时,你像最终用户一样使用foo
  • @Bakuriu 我完全同意,在个人项目中我可能会采用这种方法。不幸的是,这是我无法控制的其他人代码的文档:/

标签: python python-sphinx numpydoc


【解决方案1】:

我认为 Sphinx 中没有这样的选项。无需破解代码即可完成此操作的一种可能方法是使用自定义签名。

在这种情况下,你需要这样的东西:

.. autofunction:: some_module.foo(x, y)

这将覆盖函数的参数列表并隐藏文档中不需要的参数。

【讨论】:

    【解决方案2】:

    可以在autodoc-process-signature 事件的处理程序中编辑函数签名。

    事件处理程序的signature参数持有签名; (parameter_1, parameter_2) 形式的字符串。在下面的sn-p中,split()用来去掉函数的最后一个参数:

    hidden = "_hidden_argument"
    
    def process_sig(app, what, name, obj, options, signature, return_annotation):
        if signature and hidden in signature:
            signature = signature.split(hidden)[0] + ")" 
        return (signature, return_annotation)
    
    def setup(app):
        app.connect("autodoc-process-signature", process_sig)
    

    结果是文档将问题中函数的签名显示为foo(x, y),而不是foo(x, y, _hidden_argument=None)

    【讨论】:

      【解决方案3】:

      我同意这可能是设计不佳的症状——但我刚刚遇到了一个案例,我不得不插入一个无用的 **kwargs 参数以满足 mypy 静态类型检查器的要求...

      因此,基于 mzjn 的建议,我发布了一个简单的 sphix 扩展来隐藏文档中的参数:

      https://pypi.org/project/sphinxcontrib-autodoc-filterparams/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多