Local and Global Scope
This is an important concept, among many others. Now that we know what a function is, and how to define one, this concept can be introduced. The parameters and variables that are assigned in a called function are said to exist in the function's local scope. In other words, if we assign x = 5
inside a called function, then that x
cannot be used outside the function with the same value, unless assigned otherwise. Picking up from this, variables that are assigned outside all functions are said to exist in the global scope.
A variable that exists in a local scope is called a local variable, while a variable that exists in the global scope is called a global variable.
NOTE: A variable must be one or the other; it cannot be both local and global.
We can think of a scope as a container for variables. When a scope is destroyed, all the values stored in the scope’s variables are forgotten. There is only one global scope, and it is created when your program begins. When your program terminates, the global scope is destroyed, and all its variables are forgotten. Otherwise, the next time you ran your program, the variables would remember their values from the last time you ran it.
A local scope is created whenever a function is called. Any variables assigned in this function exist within the local scope. When the function returns, the local scope is destroyed, and these variables are forgotten. The next time you call this function, the local variables will not remember the values stored in them from the last time the function was called.
So, why do scopes matter? There are several reasons:
- Code in the global scope cannoy use any local variables
- A local scope can access global variables
- Code in any function's local scope cannot use variables in any other local scope
- We can use the same name for different variables if they are in different scopes. That is, there can be a local variable named
data
and a global variable also nameddata
.
One question that arises is, why does Python have different scopes instead of just making everything a global variable? Well, this is because when variables are modified by the code in a particular call to a function, the function interacts with the rest of the program only through its parameters and the return value. This narrows down the list code lines that may be causing a bug. If your program contained nothing but global variables and had a bug because of a variable being set to a bad value, then it would be hard to track down where this bad value was set. It could have been set from anywhere in the program—and your program could be hundreds or thousands of lines long! But if the bug is because of a local variable with a bad value, you know that only the code in that one function could have set it incorrectly.
PRO TIP: While using global variables in small programs is fine, it is a bad habit to rely on global variables as your programs get larger and larger.
Now, lets go through some cases to strengthen these concepts:
TIP: Type out the code yourself to have better practice than just copying it!
Using local variables in the global scope
What do you think? Can we do this? Will the following program work?
def myFunction():
data = 123
myFunction()
print(data)
It won't work, while printing this:
Traceback (most recent call last):
File "python.py", line 4, in <module>
print(data)
NameError: name 'data' is not defined
This error occurs because the data
variable exists only in the local scope when myFunction()
is called. Upon program execution, the local scope is destroyed and there isn't any variable data
that exists. Hence, when the program tries to run print(data)
, Python gives the error saying data
is not defined. This makes sense if you think about it; when the program execution is in the global scope, no local scopes exist, so there can’t be any local variables. This is why only global variables can be used in the global scope.
Using local variables of a function in another local scope
This is another interesting one! What do you think will happen? Lets try the following program:
def myFunction():
data = 10
newFunction()
print(data)
def newFunction():
spam = 20
data = 0
myFunction()
In this code, we call myFunction()
and then a local scope is created. The local variable data
is set to 10. After that, the newFunction()
function is called and a second local scope is created. Multiple local scopes can exist at the same time. In this new local scope, the local variable spam
is set to 20 and another local variable, different from the one in the previous function, data
is set to 0. When newFunction()
returns, the local scope for that call is destroyed. The program continues to execute in the old function, and since the local scope of this function has the value 10 for data
, it prints out 10.
To sum this, local variables in one function are completely separate from the local variables in another function.
Using global variables in the local scope
This one is easy. Consider the following program:
def myFunction():
print(data)
data = 42
myFunction()
print(data)
Since there is no parameter named data
or any code that assigns data
a value in the myFunction()
function, when data is used in myFunction()
, Python considers it a reference to the global variable data. This is why 42 is printed when the previous program is run.
Using local and global variables with the same name
PRO TIP: As a programmer, try to not use local and global variables with the same name!
It's perfectly legal in Python to have the same name variable in the local and global scope. Let's see what happens when we do that:
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
This is the output:
bacon local
spam local
bacon local
global
There are actually three different variables in this program, but confusingly they are all named eggs
. The variables are as follows:
A variable named
eggs
that exists in a local scope whenspam()
is called.A variable named
eggs
that exists in a local scope whenbacon()
is called.A variable named
eggs
that exists in the global scope.
Since these three separate variables all have the same name, it can be confusing to keep track of which one is being used at any given time. This is why you should avoid using the same variable name in different scopes.
The global
statement
What if you wish to modify a global
variable within a function? Is it possible?
In fact, it is! This is a very useful trick in Python. Looking back at an example similar to the last one,
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
The final output is:
spam
Because eggs
is declared global
at the top of spam()
, when eggs
is set to spam
, this assignment is done to the globally scoped eggs
. No local eggs
variable is created.
To sum this up, There are four rules to tell whether a variable is in a local scope or global scope:
- If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
- If there is a global statement for that variable in a function, it is a global variable.
- Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
- But if the variable is not used in an assignment statement, it is a global variable.
To make this crystal clear, check out this program:
def spam():
global eggs
eggs = 'spam' # this is the global variable
def bacon():
eggs = 'bacon' # this is a local variable
def ham():
print(eggs) # this is the global variable
eggs = 100 # this is the global variable
spam()
print(eggs)
The final output should be:
spam
IMPORTANT: If you ever want to modify the value stored in a global variable from within a function, you must use a global statement on that variable.