Variable Scope in Python
In general, a variable that is defined in a block is available in that block only. It is not accessible outside the block. Such a variable is called a local variable. Formal argument identifiers also behave as local variables.
The following example will underline this point. An attempt to print a local variable outside its scope will raise the NameError
exception.
def greet():
name = 'Steve'
print('Hello ', name)
greet()
print(name) #NameError
Here, name
is a local variable for the greet()
function and is not accessible outside of it.
Any variable present outside any function block is called a global variable. Its value is accessible from inside any function. In the following example, the name
variable is initialized before the function definition.
Hence, it is a global variable.
name='John'
def greet():
print ("Hello ", name)
greet()
print(name)
Here, you can access the global variable name
because it has been defined out of a function.
However, if we assign another value to a globally declared variable inside the function, a new local variable is created in the function's namespace. This assignment will not alter the value of the global variable. For example:
name = 'Steve'
def greet():
name = 'Bill'
print('Hello ', name) #Hello Bill
greet()
print(name) #steve
Now, changing the value of global variable name
inside a function will not affect its global value.
If you need to access and change the value of the global variable from within a function, this permission is granted by the global
keyword.
name = 'Steve'
def greet():
global name
name = 'Bill'
print('Hello ', name)
greet()
print(name) #Bill
The above would display the following output in the Python shell.
It is also possible to use a global and local variable with the same name simultaneously. Built-in function globals()
returns a dictionary object of all global variables and their respective values.
Using the name of the variable as a key, its value can be accessed and modified.
name = 'Steve'
def greet():
globals()['name'] = 'Ram'
name='Steve'
print ('Hello ', name)
greet()
print(name) #Ram
The result of the above code shows a conflict between the global and local variables with the same name and how it is resolved.
Visit Globals and Locals in Python for more information.