Link to home
Start Free TrialLog in
Avatar of David L. Hansen
David L. HansenFlag for United States of America

asked on

How does Python handle scope (ie. Private, Global, etc.) and how does it differ from .NET?

I have a python file with several variables declared right at the beginning of the code. I then have a few small classes declared (in-line inside of the same file) and finally a large loop with all the logic. What I've noticed is that at the end of the outer loop I zero-out the variable and begin again (note: the zeroing-out does work...I can see it in the debugger). The strange thing is that as soon as the loop starts again, the variables revert back to what they were when the loop completed (as if the zeroing...initializing...never happened).

I am stepping through line by line.

What am I not understanding here? Does python just deal with scope differently than other languages?

import statements
variables

class declared
class declared

outer loop:
  .
  .
  inner loop:
     .
     .
  reset variables

Open in new window

Avatar of aikimark
aikimark
Flag of United States of America image

Where are the statements that instantiate a variable based on one of the classes?
Avatar of David L. Hansen

ASKER

Sorry for the wait.

To answer your question aikinmark, line-2 represents several variable declarations. These variables never interact with the classes (line 4 and 5).

At the end of the outer-loop (see line-13) the line-2 variables are reset to zero. At that point, the outer loop can begin again. If it does, it seems that the reset of those variables never happened. The reset did happen though (at line 13) I confirmed it in debug mode.
Is it possible that the inner loop might not complete normally?  If you break out of the loop for some reason the resetting statements might not be executed.
I can step through it line by line and see everything I've described above. The variables reset on line-13 (in the watch window of VS-Code) then the program asks if I want to start again (of course line-13 represents multiple lines of code..but that's where this occurs)...to which I reply 'Yes' (all while in debug mode). The outer-loop begins again and the variables all go back to their last values before the reset.

I think it might have something to do with how Python manages 'closures' ..but I don't know.
.
.
And, at line 7 is where I see the change back to the previous values.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.