Search code examples
pythonparsingdocstring

Python docstring parsing(and generally parsing languages in Python)


I would like to generate useful documentation for a REST API written in Python.

I imagine it should be something like this:

'''
/kittens/
This method creates kittens in the browser

HTTP Params:
    format(default=json): The format in which kittens will be generated.
    count(default=10): The number of kittens to generate.

Returns:
    A list of kittens.
'''

My syntax is obviously:

program = dict
dict = repeated(name:string | name:dict)

I would like to parse this format and get (for example) a Python dict, preferably without using regex.

Is there a parser for such a syntax already available?
If not, then what is the simplest way of defining and parsing DSLs in Python?

Note that I would prefer not to use reStructuredText or any format different from what I described.


Solution

  • I'm not sure I understand exactly what you want, but reStructuredText can be used to capture the information in your example:

    .. method:: kittens(format="json", count=10)
    
       Creates kittens in the browser.
    
       :param format: The format in which kittens will be generated.
       :param count: The number of kittens to generate.
       :return: A list of kittens
    

    Sphinx understands this syntax, which is an extension of the basic reST markup defined by Docutils.