docspec-python
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
- breaking The GitHub repository for 'docspec-python' was moved from `NiklasRosenstein/docspec` to `NiklasRosenstein/python-docspec` on May 13, 2023. Users or tools referencing the old URL should update their configurations.
- gotcha The library is built 'based on lib2to3', which is a module from the Python standard library. While `lib2to3` was deprecated in Python 3.9 and removed in Python 3.10, it was partially restored in Python 3.11. Future Python versions may present compatibility challenges or require specific Python environments if `lib2to3` usage evolves.
- gotcha There are two distinct but related packages: `docspec` and `docspec-python`. `docspec` defines the JSON specification and provides the data model for API objects, along with serialization/deserialization. `docspec-python` is specifically the parser for Python source code that *produces* docspec objects. Both are often needed together.
- breaking An earlier release (0.1.1) was explicitly yanked due to a 'Breaking API change'. While this occurred in an older version, it indicates that API stability was a concern in early development.
Install
-
pip install docspec-python
Imports
- parse_python_module
from docspec_python import parse_python_module
- docspec (data model)
import docspec
Quickstart
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))