docspec-python

2.2.2 · active · verified Wed Apr 15

docspec-python is a parser based on lib2to3 that transforms Python source code into a 'docspec' data format. This data format is a JSON object specification designed for representing API documentation of programming languages, with a current focus on Python. The library allows for programmatic extraction of documentation-related information from Python modules and packages. The current version is 2.2.2 and it appears to be actively maintained with a regular release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `docspec-python` to parse a Python code string and then serialize the resulting docspec API object into a pretty-printed JSON format. It showcases parsing functions and classes along with their docstrings and type hints.

import docspec
from docspec_python import parse_python_module
import json

python_code = '''
"""A simple module.

This module demonstrates basic docstring parsing.
"""

def my_function(param1: str, param2: int) -> bool:
    """This is my function.

    :param param1: The first parameter.
    :param param2: The second parameter.
    :returns: True if param2 is even, False otherwise.
    """
    return param2 % 2 == 0

class MyClass:
    """A simple class.
    """
    def __init__(self, name: str):
        """Initialize MyClass.
        :param name: The name for the instance.
        """
        self.name = name

    def get_name(self) -> str:
        """Get the name.
        :returns: The instance's name.
        """
        return self.name
'''

# Parse the Python code string
# The 'filename' argument is optional but useful for error reporting.
module_docspec = parse_python_module(python_code, filename='my_module.py')

# Convert the docspec object to a JSON-compatible dictionary
# Use docspec.ApiObject.to_json() for this.
json_output = module_docspec.to_json()

# Pretty print the JSON output
print(json.dumps(json_output, indent=2))

view raw JSON →