0

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?).

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

10 Comments

So is there no way for the interactive terminal to pause the script somewhere inside the function, keeping variables in memory, then a single line run several times with tweaks? I thought that was the point of an interactive mode like this
By interactive terminal, do you mean a jypter notebook?
No, I think it's distinct from jupyter compatibility but might use that under the hood or something. I'm talking about the window as in "run current file in interactive window" which is an option when you right click in the editor.
The default python IDLE?
In VS Code. It's just called interactive window, it came preinstalled, or at least with the standard Python package. code.visualstudio.com/docs/python/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.