Search code examples
pythondebuggingvisual-studio-codevscode-debugger

How to view variables in parent scope while using VS Code Python Debug Console


When I set a breakpoint in a function that is imported by another script, I would like to be able to view the variables that are in the parent scope from within the VS Code Python Debug Console. Is this possible, perhaps by modifying launch.json?

Reproducible example:

I have two files, scratch_script.py and scratch_function.py. They exist in the same directory.

I place breakpoints where indicated by comments below.

Contents of scratch_script.py:

import scratch_function

parent_scope_var = 'I disappear'

scratch_function.scratch_function() # breakpoint on this line

pass # breakpoint on this line

Contents of scratch_function.py:

def scratch_function():
    child_scope_var = 'I appear'
    pass # breakpoint on this line

I run VS Code Python Debugger from scratch_script.py.

At the first break point, I can view parent_scope_var in the Python Debug Console, but not child_scope_var. So far so good.

When I proceed to the second break point, I can view child_scope_var, which is great. But now I cannot view parent_scope_var:

NameError: name 'parent_scope_var' is not defined

On the third breakpoint, the parent_scope_var is seen again in the Python Debug Console, but not the child_scope_var... Which is as I would expect.

So, my only confusion is, why can't I view parent_scope_var when pausing at breakpoints in the called function? The variable still exists, right? Just in the parent scope?


Solution

  • Yes, because when you debug to the second breakpoint, python executes the calling function. At this point, python will open the scratch_function.py file.

    First breakpoint:

    enter image description here

    Second breakpoint:

    enter image description here

    it will only display the variables that exist in the current file, and there is no parent_scope_var variable in the scratch_function.py file, the python interpreter cannot find parent_scope_var, so the watch panel prompts an error: NameError: name 'parent_scope_var ' is not defined.

    enter image description here

    But as you might guess, the variable still exists at this point, just inside the scratch_script.py file. At this point, you can open the scratch_script.py file, hover the mouse over the parent_scope_var variable, and vscode will clearly show you the variable value at this time.

    enter image description here

    On a side note, you can also see the previous parent_scope_var variable in the CALL STACK panel.

    enter image description here

    PS: a setting to display variable values inline in code files when debugging:

    //file:settings.json
    {
        "debug.inlineValues": "on",  
    }