So most auto-docstring generation tools typically generate the docstring once based on the function signature when you first create it, but subsequent changes to the parameters need to be manually updated in the docstring.
You can use Python's ast module to parse your Python file, detect function definitions, and update docstrings according to function signature.
import ast
import astor
class DocstringUpdater(ast.NodeTransformer):
def visit_FunctionDef(self, node):
#########################################
# This block of code generates a new docstring
# for the function definition node. If no docstring
# exists, it adds one. If a docstring exists, it
# replaces the existing one with the new docstring.
#########################################
new_docstring = self.generate_docstring(node)
if ast.get_docstring(node) is None:
#########################################
# If no docstring exists, add one
#########################################
node.body.insert(0, ast.Expr(value=ast.Str(s=new_docstring)))
else:
#########################################
# If docstring exists, replace it
#########################################
node.body[0].value.s = new_docstring
return node
def generate_docstring(self, node):
#########################################
# This function generates a new docstring
# based on the function's arguments.
#########################################
param_docs = []
for arg in node.args.args:
param_docs.append(f" {arg.arg} : type\n Description")
if param_docs:
param_docs_str = "\n".join(param_docs)
return f"""{node.name}
Args:
{param_docs_str}
Returns:
type: Description
"""
else:
return f"""{node.name}
Returns:
type: Description
"""
def update_docstrings(file_path):
#########################################
# This function reads a Python file, parses it
# into an AST, updates the docstrings, and writes
# the updated AST back to the file.
#########################################
with open(file_path, 'r') as file:
tree = ast.parse(file.read())
updater = DocstringUpdater()
updated_tree = updater.visit(tree)
with open(file_path, 'w') as file:
file.write(astor.to_source(updated_tree))
#########################################
# Usage example
# Specify the path to your Python file
# and update the docstrings.
#########################################
file_path = 'main.py'
update_docstrings(file_path)