Thomas Dewitt
Thomas Dewitt

Reputation: 60

How to use Python Interactive Window in VS Code with functions

I am new to using the python interactive window and I like it but it seems to clear local variables in between runs, so if I run something like


def main():
    dates = '2012152'
    # %%
    print(dates)              # want to just run this

    # %%


if __name__ == '__main__':
    main()

# or even
main()

all at once it works fine but then if I just run the middle cell I get "dates not defined" error. It works outside of the function because apparently a global variable is saved:

dates = '2012152'
# %%
print(dates)             # this works if this cell is run

# %%

Is there any way to get a similar behavior inside a function? If not it doesn't seem useful to me at all (maybe I have designed my code badly?).

Upvotes: 0

Views: 2287

Answers (2)

Radzor
Radzor

Reputation: 194

Cells are a great way to experiment with flat code, but they are limited when working nested inside functions. One way to work around this is to use a regular built-in python debugger and set a breakpoint within the function.

Here is a process I use for experimenting with code inside a function:

  1. Set a breakpoint in the function, after the code you want to experiment with and start debugging.
  2. Make any necessary changes to the code.
  3. Select the lines that you've changed and that you want to run again. Make sure to include all the indentations as well.
  4. Right-click and select Evaluate in Debug Console.

This will allow you to run the code one line at a time, see results, and make any necessary adjustments as you go along.

The process could be further improved by binding a keyboard shortcut to the this command.

Upvotes: 1

SuPythony
SuPythony

Reputation: 915

Yes, print(dates) will not run as the dates variable isn't in scope, unless the function main is called and even then dates will be only in the local scope of the function, not in global scope.

So to print it outside the function, you need to first define it.

Upvotes: 0

Related Questions