Global, Local and Nonlocal Variables in Python

In this Python article, we will discuss the three keywords namely the Global, local and nonlocal along with suitable examples and implementation. So let’s get started.

1. What is variable scope in Python?

As discussed in the namespace tutorial, the scope of a variable is the accessibility associated with it in a proper context.

If we define variables in a class or a function then they are limited to the class or function and will be termed local but if they are declared outside then global.

There is one more category that is nonlocal. Nonlocal variables are defined as variables that are neither global nor local.

Now we will discuss each of them in detail.


2. What are Global variables and their uses?

In python, when we declare the variables outside the function’s body or in global scope then they are termed as global variables as they have a global scope.

In every language, whether it be Java, C, C++, Python, a variable that is accessible by any line in the program is a global variable.

One thing to remember is that changes cannot be made to a global variable by using any function. If we do so, the changes will be isolated to a local variable inside the functions and it won’t affect the global variable unless used with the global keyword.

2.1. Use global variables inside function

Let’s implement a program to see the usage of the global variable inside a function.

count = 5

def check():
  print('Inside funtion', count)

check()
print('Outside funtion', count)
Output
Inside funtion 10
Outside funtion 5

Now let us look at what happens when we try to change the global value through a function without using a global keyword.

colour = ['Green', 'White', 'Orange', 'Blue']


def try_update():
  # local variable created
  colour = ['Green', 'White', 'Orange']
  print('Inside funtion', colour)


try_update()
# global variable unaffected
print('Outside funtion', colour)
Output
Inside funtion ['Green', 'White', 'Orange']
Outside funtion ['Green', 'White', 'Orange', 'Blue']

2.2. Use of global keyword

As seen in the above example, the changes made to the variable named similar to the global variable were not reflected in the global variable. But what can we do if we want to make the change to the global variable?

If we want to make changes to the global variable, we will use the global keyword.

Let’s take an example to understand it.

colour = ['Green', 'White', 'Orange', 'Blue']

def try_update():
  global colour
  colour = ['Green', 'White', 'Orange']
  print('Inside funtion', colour)

try_update()
# global variable updated
print('Outside funtion', colour)
Output
Inside funtion ['Green', 'White', 'Orange']
Outside funtion ['Green', 'White', 'Orange']

Here in the above example, the context of the variable was referring to the global variable.

So, when we declare using the global keyboard we explicitly define that we want to use the global variable and Python should not create any local variable.

2.3. Updating a global variable

Changes made to the variable are reflected in the global scope and are reflected even outside the function.

Note: Changes to the global variable have to be done with caution as overriding the scope or overwriting the scope may end up with lots of bugs and abrupt behavior. So, we must modify the variable according to its context.

Let’s look what cautions are we talking about with a short example.

colour = ['Green', 'White', 'Orange', 'Blue']
def start_item():
  global colour
  colour = colour[0]
  
def iterate_all():
  global colour
  for i in colour:
        print(i)
    
iterate_all()
print(colour)
start_item()
print(colour)
Output
Green
White
Orange
Blue
['Green', 'White', 'Orange', 'Blue']
Green

Here, in the above example, everything is working fine when we have called the iterate_all() and then the start_item(). Now let’s see what happens after we reverse the order of iteration_all and start_item.

colour = ['Green', 'White', 'Orange', 'Blue']
def start_item():
  global colour
  colour = colour[0]  

def iterate_all():
  global colour
  for i in colour:
        print(i)
    
start_item()
print(colour)
iterate_all()
print(colour)
Output
Green
G
r
e
e
n
Green

In the above example, the variable colour has become a string that gets iterated through. It may be possible that this bug will not come up until it’s too late. It first looked to run fine.

As visible, we tampered with the global variable directly and changed its value. However. In more complex structures, this kind of accidental change to the global variable may step too far and end up giving unexpected results.

So as a thumb rule either try to use immutable objects or do not update the global variables at all to have less complex structures and better code quality.


3. What is local variable?

As already described, those variables which are defined inside a function or class (as an instance variable) or in a local scope are termed as local variables.

def name_list():
  names = ['James', 'Jonas', 'Jodua', 'John']
  print(names)
   
name_list()
Output
['James', 'Jonas', 'Jodua', 'John']

The local variable unlike the global variables, cannot be called outside their defined section. If we try to do so, we will get an error.

Let’s look at how it will throw an error if we try to access the local variable outside the method.

def name_list():
  names = ['James', 'Jonas', 'Jodua', 'John']    

print(names)
Output
Traceback (most recent call last):
  File "C:/Users/ASUS/Documents/fakegloballocal.py", line 3, in 
    print(names)
NameError: name 'names' is not defined

3.1. Use global and local variable together

We can use global and local variables inside one function and also we can use the same variable name for both local and global calls.

Let’s understand how it works with an example.

str = "Coder"
def call():
  global str
  str_local = "Programmer"
  str = str * 2
  print(str)
  print(str_local)

call()

#Same name variable for local&global
value = 3
def check():
  value = 30
  print("local value:", value)

check()
print("global value:", value)
Output
CoderCoder
Programmer
local value: 30
global value: 3                     

In the above example, when we print the variable present inside the function check() it gives local value: 30. ( local scope of the variable) and when we print the variable present outside the function check(), it gives global value: 3. ( global scope of the variable)


4. How to use Non Local variables?

nonlocal variables are used in nested functions when we want to use the variable defined in the outer method local scope. The nonlocal variable can neither be in the local nor in the global scope.

We discussed the caution of updating the global variables and one of the ways to ensure that we are not updating the global variable is to use the nonlocal keyword.

If we declare a variable within a function and we want to update that variable within a nested function without providing any return statement for the same, we can do that with the help of a nonlocal keyword.

Let’s create one non local variable by a small example.

str = "Global"
def outer_func():
  str = "Outer"

  def inner_func():
    nonlocal str
    str = "Inner"
    print("Result from the inner function:", str)

  inner_func()
  print("Result from the outer function:", str)

outer_func()
print("Result from the global scope:", str)
Output
Result from the inner function: Inner
Result from the outer function: Inner
Result from the global scope: Global

Here in the above example, we have a nested inner_func() function. We have used the nonlocal keyword to create a nonlocal variable and update a variable that is originally defined in outer_func().


5. Conclusion

In this article we learned about

  • A brief idea about the Scope in Python
  • Global variables and their uses along with useful and understandable examples
  • How can we use the Global Keyword?
  • What are Local variables and also the use Non Local variables?

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index