Generate Python docstrings & comments

Generate docstrings and comments for Python functions.

You can query a model directly and test the results returned when using different parameter values with the Cloud console, or by calling the Vertex AI API directly.

Prompt Freeform

Here is Python code. Insert a document comment (docstring) for all functions, including the nested functions.

def is_dag_dfs(graph): visited = set() on_stack = set() # Track nodes on recursion stack

def dfs(node):
    if node in on_stack:
        return False  # Back-edge found (cycle)
    if node in visited:
        return True

    on_stack.add(node)
    visited.add(node)

    for neighbor in graph.get(node, []):
        if not dfs(neighbor):
            return False

    on_stack.remove(node)
    return True

return all(dfs(node) for node in graph)

Response

def is_dag_dfs(graph):
    """Checks if a directed graph is a Directed Acyclic Graph (DAG).

    This function uses a Depth-First Search (DFS) approach. It maintains two sets:
    'visited' to keep track of all nodes that have been visited, and 'on_stack'
    to keep track of nodes currently in the recursion stack for the current DFS
    path. A cycle is detected if a node is encountered that is already on the
    recursion stack (a back-edge).

    Args:
        graph (dict): A dictionary representing the graph as an adjacency list.
                      Keys are the nodes, and values are lists of their
                      neighboring nodes (to which they have an outgoing edge).
                      Example: {'A': ['B', 'C'], 'B': ['D']}

    Returns:
        bool: True if the graph is a DAG, False otherwise.
    """
    visited = set()
    on_stack = set()  # Track nodes on recursion stack

    def dfs(node):
        """Recursively performs a Depth-First Search from a given node.

        This helper function explores the graph, using the 'on_stack' set from
        the parent scope to detect cycles and the 'visited' set to avoid
        re-processing nodes.

        Args:
            node: The node to start the DFS from.

        Returns:
            bool: False if a cycle is detected in the path starting from this
                  node, True otherwise.
        """
        if node in on_stack:
            return False  # Back-edge found (cycle)
        if node in visited:
            return True

        on_stack.add(node)
        visited.add(node)

        for neighbor in graph.get(node, []):
            if not dfs(neighbor):
                return False

        on_stack.remove(node)
        return True

    return all(dfs(node) for node in graph)

Model: gemini-2.5-pro
Temperature: 0.2
Max output tokens: 8192
TopK: 40.0
TopP: 0.95