In Sphinx, is there a way to document parameters along with declaring them?

前端 未结 3 1755
礼貌的吻别
礼貌的吻别 2021-02-20 09:43

I prefer to document each parameter (as needed) on the same line where I declare the parameter in order to apply D.R.Y.

If I have code like this:

def foo         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 10:02

    I would do this.

    Starting with this code.

    def foo(
            flab_nickers, # a series of under garments to process
            has_polka_dots=False,
            needs_pressing=False  # Whether the list of garments should all be pressed
       ):
        ...
    

    I would write a parser that grabs the function parameter definitions and builds the following:

    def foo(
            flab_nickers, 
            has_polka_dots=False,
            needs_pressing=False,
       ):
       """foo
    
       :param flab_nickers: a series of under garments to process
       :type flab_nickers: list or tuple
       :param has_polka_dots: default False
       :type has_polka_dots: bool
       :param needs_pressing: default False, Whether the list of garments should all be pressed
       :type needs_pressing: bool
       """
        ...
    

    That's some pretty straight-forward regex processing of the various arguments string patterns to fill in the documentation template.

    A lot of good Python IDEs (for example PyCharm) understand the default Sphinx param notation and even flag vars/methods in the scope that IDE thinks does not conform to the declared type.

    Note the extra comma in the code; that's just to make things consistent. It does no harm, and it might simplify things in the future.

    You can also try and use the Python compiler to get a parse tree, revise it and emit the update code. I've done this for other languages (not Python), so I know a little bit about it, but don't know how well supported it is in Python.

    Also, this is a one-time transformation.

    The original in-line comments in the function definition don't really follow DRY because it's a comment, in an informal language, and unusable by any but the most sophisticated tools.

    The Sphinx comments are closer to DRY because they're in the RST markup language, making them much easier to process using ordinary text-parsing tools in docutils.

    It's only DRY if tools can make use of it.

    Useful links: https://pythonhosted.org/an_example_pypi_project/sphinx.html#function-definitions http://sphinx-doc.org/domains.html#id1

提交回复
热议问题