Search code examples
pythonvisual-studio-codeterminal

In VS Code, when sending Python lines to terminal, why do I have to re-send lines that set a variable to an edited value before the lines that use it?


When I write code in VS Code and i run it everything is fine, but when i change something to the code and hit ctrl + s the changes aren't updated or ran in the terminal.

For example changing the value of a variable that i want to print, when i execute the print after saving the changes to the variable with ctrl + s it prints the same value as the previous one that was affected to the variable.

The only work around (which i though was normal before a friend noticed me it wasn't) was to run with shift + enter the selected code i wanted to update for the changes to take effect.

In other words i have to shift + enter the code that i want to update the print result in my terminal regardless if it is saved or not.

Example

Before changes :

a = 1
b = 1
print(a+b)

output : 2

After changes and a ctrl + s :

a = 1
b = 2
print(a+b)

output : 2

Solution

  • The Python interpreter running in your terminal has state. If you only rerun the print line after changing the lines that set the variables to different values, you haven't told the interpreter to update its state with respect to those variables. That's just how it works. Only the lines that are sent to the Python interpreter will be run (to update its state or perform some other action). There's no fancy data dependency detection going on in the Python extension for VS Code with respect to sending lines to the terminal (though there are are some other program analysis things going on).