[Python] How to debug code and visualize the execution

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I'm taking open-source class. I am given doctests and a CLI to test my code and see if it passes, however, how can I visualize my code to see what is happening? For instance, I am having a hard time understanding how the for loop is working and I would like to see what list is assigned in each recursion.

    The file has many functions so running -m doctest isn't ideal and also doesn't show the execution. When I run debug mode in vs code and set a breakpoint at the function, it never steps into the function. I imagine this is because in the file I never call nut_finder() but I don't want to start adding to the source code since that would defeat the purpose of the doctest. I can also run python interactively but that too won't show me how the code is executing.

    The only solution I have found is to use a tool that visualizes the code, however, this requires me to manually copy and paste stuff. This also will become a problem from large applications and multi-file applications. So in short, how can I learn the right way to debug my code.

    # lab05.py
    def nut_finder(t):
    """Returns True if t contains a node with the value 'nut' and
    False otherwise.

    >>> scrat = tree('nut')
    >>> nut_finder(scrat)
    True
    >>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('nut')]), tree('branch2')])
    >>> nut_finder(sproul)
    True
    >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
    >>> nut_finder(numbers)
    False
    >>> t = tree(1, [tree('nut',[tree('not nut')])])
    >>> nut_finder(t)
    True
    """
    if label(t) == 'nut':
    return True
    for b in branches(t):
    if nut_finder(b):
    return True
    return False

    Continue reading...

Compartilhe esta Página