Is there a way to auto-update python auto-docstrings with new/modified parameters?
Asked Answered
D

3

21

I am using VS Code as my editor and autoDocstring as the auto-docstring generator extension for Python. There are times when I modify the parameters of a function, either by introducing new parameters or by modifying their names, default values etc. I am required to make manual changes to the docstring in such cases.

Is there any way that the docstring gets auto-updated as I change the function signature? At least the introduction of new parameters to the docstring section.

Dzoba answered 30/4, 2022 at 2:42 Comment(7)
why not create a PR for the extension, implement the behavior you wantPeristalsis
If you use the IDE's builtin refactor it should inspect docstrings and comments and offer to update them.Orvas
@Orvas - I am using VS Code. I tried the refactor facility in there but nothing happened. Could you please provide an example with maybe a few screenshots? Any editor in which you might have found the result will do.Dzoba
@AnirbanChakraborty PyCharm will catch the names, but won't refactor the types, or descriptions automatically.Orvas
If using sphinx to generate html for the docs, there are a lot of plugins that can avoid the duplication (and therefore the human error). E.g. default-values allows injecting the default value into the generated docs, and sphinx-autodoc-typehints can convert the type hints into the docs as well. In these cases, all you need to do is make sure the name matches, and the rest will follow.Reproachful
@flakes, but that's for generated documentation, what about simple docstrings of functions? My gut feeling is that this should be very straightforward and the functionality probably exists, I simply don't know what words I have to look for.Cushiony
It's not a solution to what you asked but you can cut the existing docstring and generate the docstring again that would have updated names/parameters/typehints and then fill in the existing details to avoid manual editing and hence potential mistakes.Mayhap
E
4

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)
Eyesight answered 23/5, 2024 at 18:31 Comment(2)
This is too much work isn't it? I'd rather update manually at this point!Forespent
It depends on how skilled you are as a programmer. An associate versus senior versus architect will all resolve this with different effort levels.Eyesight
N
1

Try using trelent extension to create docstrings in VSCode. It gives us an option to update docstring once we update any function parameters. I have been using it for some time and it solves this issue perfectly.

enter image description here

Nomadize answered 28/5, 2024 at 9:36 Comment(0)
Q
1

Recommending AI Docstring Generator Extension in VS code , which has support Create and Update the Docstrings if there are any changes / updates happened.

enter image description here

Quitrent answered 29/5, 2024 at 15:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.