Documenting with Sphinx python methods that do have default parameters with sentinel objects?

孤人 提交于 2019-12-04 04:40:14

问题


If you want to be able to allow people to call some methods using None you have to do use a sentinel object when you define the method.

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

This would allow you to call foo(param1=None) and be able to make the difference between a call like foo().

The problem is that when Sphinx does document the method it will write something like

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

How can I convince Sphinx to have a user friendly output for these functions?

Note, Imagine how the documentations look if you have 3-4 parameters using the sentinel approach.


回答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:
         ... 



回答2:


This can be handled by manually specifying function signature in autodoc directive, e.g.:

.. automodule:: pymorphy.contrib.tokenizers

    .. autofunction:: extract_tokens(foo, bar)

    .. autofunction:: extract_words



回答3:


The <object object at 0x108c1a520> part of generated method signature can be changed by overriding the __repr__ method of the sentinel object.

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

It will be rendered by Sphinx as something like this:

mymodule.foo(param1=_sentinel)


来源:https://stackoverflow.com/questions/6978328/documenting-with-sphinx-python-methods-that-do-have-default-parameters-with-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!