Scoping in Python 'for' loops

enclosing scope python
python block scope
python scope rules
python scope if
namespace in python
global variable python
python nested function scope
python global

I'm not asking about Python's scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended):

for foo in xrange(10):
    bar = 2
print(foo, bar)

The above will print (9,2).

This strikes me as weird: 'foo' is really just controlling the loop, and 'bar' was defined inside the loop. I can understand why it might be necessary for 'bar' to be accessible outside the loop (otherwise, for loops would have very limited functionality). What I don't understand is why it is necessary for the control variable to remain in scope after the loop exits. In my experience, it simply clutters the global namespace and makes it harder to track down errors that would be caught by interpreters in other languages.

The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of assignment statements. The global keyword exists just for this reason (to signify that assignment is done at a global scope).


Here's a good discussion on the topic:

Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature.

In short, you can probably blame it on the Python community :P

Python Scope, Scope refers to the coding region from which particular Python object is accessible. Hence one cannot access any particular object from anywhere from the code,� Scope Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used. Python supports global variables (usable in the entire program) and local variables. By default, all variables declared in a function are local variables.

Python does not have blocks, as do some other languages (such as C/C++ or Java). Therefore, scoping unit in Python is a function.

Namespaces and Scope in Python, These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables. Then after, you will revisit� Scope of Objects in Python : Scope refers to the coding region from which particular Python object is accessible. Hence one cannot access any particular object from anywhere from the code, the accessing has to be allowed by the scope of the object. Lets take an example to have details understanding of the same: Example 1:

A really useful case for this is when using enumerate and you want the total count in the end:

for count, x in enumerate(someiterator, start=1):
    dosomething(count, x)
print "I did something {0} times".format(count)

Is this necessary? No. But, it sure is convenient.

Another thing to be aware of: in Python 2, variables in list comprehensions are leaked as well:

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> x

But, the same does not apply to Python 3.

(Tutorial) Scope of Variables in Python, Defining variables�. To define a new variable in Python, we simply assign a value to a label. For example, this is how we create a variable called� The Python scope concept is generally presented using a rule known as the LEGB rule. The letters in the acronym LEGB stand for Local, Enclosing, Global, and Built-in scopes. This summarizes not only the Python scope levels but also the sequence of steps that Python follows when resolving names in a program. In this tutorial, you’ll learn:

If you have a break statement in the loop (and want to use the iteration value later, perhaps to pick back up, index something, or give status), it saves you one line of code and one assignment, so there's a convenience.

Variables and scope — Object-Oriented Programming in Python 1 , The scope of a variable refers to the places that you can see or access a variable. If you define a variable at the top level of your script or module or notebook, this� The scope determines the parts of the program where you could use that name without any prefix. Python outlines different scopes for locals, function, modules, and built-ins. Check out from the below list. A local scope, also known as the innermost scope, holds the list of all local names available in the current function.

One of the primary influences for Python is ABC, a language developed in the Netherlands for teaching programming concepts to beginners. Python's creator, Guido van Rossum, worked on ABC for several years in the 1980s. I know almost nothing about ABC, but as it is intended for beginners, I suppose it must have a limited number of scopes, much like early BASICs.

Global and local scope of Python variables — Tutorials on imaging , Python Scope, a Beginner's Guide. Scope Variables can only reach the area in which they are defined, which is called scope. Think of it as the� In statically typed languages, variables have predetermined types, and a variable can only be used to hold values of that type. In Python, we may reuse the same variable to store values of any type. A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times, and that storing a new value erases the old.

Python Scope, a Beginner's Guide - Python Tutorial, Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it � Next, you will get familiar with the boundary of variables within a program - its "scope". You will learn about the four different scopes with the help of examples: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.

Short description of the scoping rules?, This is a short tutorial about Python's namespaces and the scope resolution for variable names using the LEGB-rule. The following sections will� Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class's namespace, but they are not directly accessible from within the methods (or nested classes) they contain.

A Beginner's Guide to Python's Namespaces, Scope Resolution , In this Python Tutorial, we will be going over variable scope in Python. Scope is important Duration: 20:59 Posted: 20 Dec 2016 Static Scoping: Static scoping is also called lexical scoping. In this scoping a variable always refers to its top level environment. This is a property of the program text and unrelated to the run time call stack. Static scoping also makes it much easier to make a modular code as programmer can figure out the scope just by looking at the code.

  • If you don't want the for loop cluttering your global namespace, wrap it in a function. Closures galore!
  • Unless you're running a loop in the global namespace (uncommon), it's cluttering a local namespace.
  • If this didn't exist, how would you continue processing later at the point you left off inside the loop? Just define the control variable before the loop?
  • @endolith Yeah... Why not require that?
  • well people are just gonna prefer what they're used to doing. I'd say this sort of thing hurts the python coder who gets used to this sort of thing and has to go through a painful process when switching to a different language. For the rest of us, it's a neat little shortcut I suppose.
  • How would the grammar be more complicated if the scope of the induction variable were limited to the body of the loop? Such a change would be confined to the semantic analysis in Python, not to its grammar.
  • Loops are not blocks in Python. This sort of behavioral change would call for either changing the grammar fundamentally or providing a special case. The whole concept of an induction variable is also not expressed in the current grammar. The grammar provides the contract for how the interpreter will interpret. My point is that I cannot foresee how a change in this behavior can be done without making the grammar more complicated. It's all moot since the side effect of the design decision has become a feature.
  • This post here gives more details regarding speed and complication which Mr. Brown alludes to.
  • I'm confused - what prevents Python from scoping for loops the same way that functions are scoped?
  • Not really true, it's just that the grammar doesn't go block-crazy. (…) "A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition..."
  • @thebackhand, nothing. It was just deemed unnecessary.