4

Consider this example:

for iter in xrange(10):
   myvar = iter

print myvar
# 9

Here myvar is clearly outside the loop? But it is still accessible. If this is Perl, it will throw an error.

What's the reason behind such feature in Python? Is it harmful? What's the best practice then, to declare a variable before looping?

pdubois
  • 7,640
  • 21
  • 70
  • 99
  • 6
    http://stackoverflow.com/questions/3611760/scoping-in-python-for-loops – galaxyan Nov 11 '15 at 03:40
  • There is global scope and function (local) scope. There isnt block level scope. This is a side effect of having such a simple scheme. – RobertB Nov 11 '15 at 03:48

2 Answers2

6

There is no new scope created by the for loop (Ruby also behaves the same way). This may be surprising if you are coming from a language that creates new scopes for blocks.

I don't believe it's harmful as long as you know the rules.

If your functions and methods are so large that you have trouble keeping track, then your functions and methods are too large.

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
-1

Think of it as if you're doing this:

my_var = 0
my_var = 1
my_var = 2
...
my_var = 9

print my_var

This is basically what the iteration will look like, there is no reason why my_var would not be accessible from within your current method / scope.

veggie1
  • 717
  • 3
  • 12