The scope of an identifier is defined to be the portion of the program where its declaration applies, or what we refer to as “variable visibility.” In other words, it is like asking yourself in which parts of a program do you have access to a specific identifier. Variables either have local or global scope.
Global vs. Local Variables
Variables defined within a function have local scope, and those which are at the highest level in a module have global or nonlocal scope. In their famous “dragon” book on compiler theory, Aho, Sethi, and Ullman summarize it this way:
“The portion of the program to which a declaration applies is called the scope of that declaration. An occurrence of a name in a procedure is said to be local to the procedure if it is in the scope of a declaration within the procedure; otherwise, the occurrence is said to be nonlocal.” One characteristic of global variables is that unless deleted, they have a lifespan that lasts as long as the script that is running and whose values are accessible to all functions, whereas local variables, like the stack frame they reside in, live temporarily, only as long as the functions they are defined in are currently active. When a function call is made, its local variables come into scope as they are declared. At that time, a new local name is created for that object, and once that function has completed and the frame deallocated, that variable will go out of scope.
>>> global_str = "foo" >>> def foo(): local_str = "bar" return blobal_str + local_str
In the above example, global_str is a global variable while local_str is a local variable. The foo() function has access to both global and local variables while the main block of code has access only to global variables.
When searching for an identifier, Python searches the local scope first. If the name is not found within the local scope, then an identifier must be found in the global scope or else a NameError exception is raised.
Global variable names can be overridden by local variables if they are declared within the function. Here is another example, similar to the first, but the global and local nature of the variable is not as clear.
def foo(): print "ncalling foo()…" bar = 200 print "in foo(), bar is", bar bar = 100 print "in __main__, bar is", bar foo() print "nin __main__, bar is (still)", bar