3

如果您希望能够允许人们使用您调用某些方法,则必须在定义方法时None使用哨兵对象。

 _sentinel = object()
 def foo(param1=_sentinel):
     ...

这将允许您拨打电话foo(param1=None)并能够在电话之间有所不同,例如foo().

问题是,当 Sphinx 确实记录该方法时,它会编写类似

mymodule.foo(param1=<object object at 0x108c1a520>)

如何说服 Sphinx 为这些功能提供用户友好的输出?

请注意,想象一下如果您使用哨兵方法有 3-4 个参数,文档的外观。

4

3 回答 3

1

I don't think it is possible to persuade Sphinx to be more "friendly" as long as you have a sentinel that creates an object outside the function. Sphinx' autodoc extension imports the module, which means that module-level code is executed.

Are you sure you can't use something like this?

def foo(param1=None):
    if param1 == None:
        param1 = whatever you want...
    else:
         ... 
于 2011-08-08T18:45:12.167 回答
1

这可以通过在 autodoc 指令中手动指定函数签名来处理,例如:

.. automodule:: pymorphy.contrib.tokenizers

    .. autofunction:: extract_tokens(foo, bar)

    .. autofunction:: extract_words
于 2011-08-08T20:38:17.903 回答
0

生成的<object object at 0x108c1a520>方法签名部分可以通过覆盖__repr__哨兵对象的方法来更改。

_sentinel = type('_sentinel', (object,),
                 {'__repr__': lambda self: '_sentinel'})()

它将由 Sphinx 呈现为如下所示:

mymodule.foo(param1=_sentinel)
于 2018-05-05T19:33:18.183 回答