0

What happens to variables assigned for the first time (defined) inside if statement or for loop if long time passed from when their code run. Is there some sort of garbage collection that may result in a not defined variable exception. For example:

if True:
   a=1
else:
   a=3
# long time passed and other codes run
# .
# .
# .
print (a)

I encountered an error in my code that I suspect this to be the reason. Is it documented somewhere in official Python documentation ?

Ehsan88
  • 3,569
  • 5
  • 29
  • 52
  • 3
    Unless your variables moves out of scope it should not be garbage collected. Thats how ref counting works (the way Python garbage collects). – Games Brainiac Aug 18 '14 at 18:22
  • 1
    variables stay, as long as the scope exists, unless they are removed by `del a`. – Daniel Aug 18 '14 at 18:26
  • Why do you suspect that is the reason? The code you post doesn't come close to reproducing your suspected error. – chepner Aug 18 '14 at 18:42
  • could u try print(a) right after the if else statement as a way of debugging? –  Aug 18 '14 at 18:50
  • 2
    possible duplicate of [What's the scope of a Python variable declared in an if statement?](http://stackoverflow.com/questions/2829528/whats-the-scope-of-a-python-variable-declared-in-an-if-statement) – skrrgwasme Aug 18 '14 at 19:10
  • @ScottLawson yes it's a duplicate. Thanks! – Ehsan88 Aug 18 '14 at 19:14

1 Answers1

1

In Python, if you define a variable within an if statement, it will continue to exist after the if statement concludes. Scopes are defined for a class, a def, or the global scope; if you're in a function and you define a variable inside if, for example, that variable will exist until the function is done executing.

Be careful, however, of defining variables in code like this:

if x == True:
  a = 1
else:
  print "Not true"

If you have code like this, and x ends up being False, then a will not be defined. Later calls to a will throw an exception as a result. So make sure that you get rid of any potential problems of that sort.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42