Reputation: 60
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
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:
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
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