Docspec
Docspec is a JSON object specification for representing API documentation of programming languages. While in its current form it primarily targets Python APIs, it was designed to be extensible to cover a more generalized set of languages. It also provides a Python module for the (de-)serialization and in-memory modification of docspec-conformant JSON payloads. The current version is 2.2.2 and it follows a feature-driven release cadence.
Warnings
- breaking The official GitHub repository for 'docspec' was moved from `NiklasRosenstein/docspec` to `NiklasRosenstein/python-docspec` on May 13, 2023. Old links or git clone commands pointing to the former URL will no longer work.
- gotcha There are two related packages: `docspec` and `docspec-python`. Users often confuse them. `docspec` provides the specification and library for handling the JSON data structure. `docspec-python` is a *parser* that takes actual Python source code and generates `docspec`-conformant JSON data. You typically need both if you want to extract docs from Python code.
- gotcha `docspec` itself (the core library) does not contain functionality to parse Python source code or any other programming language. Its purpose is to deserialize, work with, and serialize the language-agnostic Docspec JSON format.
Install
-
pip install docspec
Imports
- docspec
import docspec
Quickstart
import docspec
from io import StringIO
# Example of a docspec-conformant JSON payload for a simple module
# In a real-world scenario, this might come from a file or from docspec-python.
example_json_input = '''
{
"name": "example_module",
"location": {"filename": "example_module.py", "lineno": 1},
"docstring": "A module demonstrating docspec structure.",
"members": [
{
"name": "my_function",
"type": "function",
"location": {"filename": "example_module.py", "lineno": 3},
"docstring": "This is a sample function.",
"args": [],
"returns": null,
"decorations": [],
"is_async": false
}
]
}
'''
# Load module(s) from a JSON string (simulating file input)
modules = docspec.load_modules(StringIO(example_json_input))
# Iterate and process loaded modules
for module in modules:
print(f"\nProcessing Module: {module.name}")
print(f" Module Docstring: {module.docstring}")
# Example: Filter members to only include those with docstrings
original_members_count = len(module.members)
module.members = [member for member in module.members if member.docstring]
print(f" Original member count: {original_members_count}")
print(f" Members with docstrings after filtering: {[m.name for m in module.members]}")
# To dump the modified module back to JSON (e.g., to stdout or a file):
# from sys import stdout
# for module in modules: # Assuming 'modules' might have multiple
# docspec.dump_module(stdout, module)