In this article we will discuss difference between local & global variable and will also see ways to access / modify both same name
global & local variable inside a function.
Table of Contents
- Local variable vs Global variable
- Global & local variables with same name
- Use of “global†keyword to modify global variable inside a function
- Using globals() to access global variables inside the function
- Handling UnboundLocalError Error
- The Complete example of global variable and globals() in Python
Local variable vs Global variable
Local variable is a variable that is defined in a function and global variable is a variable that is defined outside any function or class i.e. in
global space. Global variable is accessible in any function and local variable has scope only in the function it is defined. For example,
# Global variable total = 100 def test(): # Local variable marks = 19 print('Marks = ', marks) print('Total = ', total)
Here 'total' is a global variable therefore accessible inside function test() too and 'marks' is a local variable i.e. local to function test() only. But what if we have a scenario in which both global & local variables has same name ?
Global & local variables with same name
Checkout this example,
total = 100 def func1(): total = 15 print('Total = ', total) func1() print('Total = ', total)
Output:
Total = 100 Total = 100
Here 'total' is a global variable and func() function has a local variable with same name. By default a function gives preference to
local variable over global variable if both are of same name. Therefore in above code when we modified 'total' variable inside the function then it was not reflected outside the function. Because inside function func() total variable is treated as local variable.
But what if want to access global variable inside a function that has local variable with same name ?
Frequently Asked:
- Return multiple values from a function in Python
- Python : filter() function | Tutorial & Examples
- How to break out from multiple loops python?
- Functions in Python
Use of “global†keyword to modify global variable inside a function
If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.
global total
It will make the function to refer global variable total whenever accessed. Checkout this example,
total = 100 def func(): # refer to global variable 'total' inside function global total if total > 10: total = 15 print('Total = ', total) func() print('Total = ', total)
Output:
Total = 100 Total = 15
As you can see modification done to global variable total is now visible outside the function too.
When we use global keyword with a variable inside the function then the local variable will be hidden. But what if we want to keep bot the local & global variable with same and modify both in the function ? Let's see how to do that,
Using globals() to access global variables inside the function
As 'global' keywords hide the local variable with same name, so to access both the local & global variable inside a function there is an another way i.e. global() function.
globals() returns a dictionary of elements in current module and we can use it to access / modify the global variable without using 'global' keyword i,e.
total = 100 def func3(): listOfGlobals = globals() listOfGlobals['total'] = 15 total = 22 print('Local Total = ', total) print('Total = ', total) func3() print('Total = ', total)
Output:
Total = 15 Local Total = 22 Total = 11
As you can see that we have local variable and global variable with same name i.e. total and we modified both inside the function. By using dictionary returned by globals() to refer global variable instead of keyword 'global'. It will not hide local variable inside the function.
Handling UnboundLocalError Error
If we try to access a global variable with 'global' keyword or globals() inside a function i.e.
total = 22 def func2(): if total > 10: total = 15
It will throw an error like this,
UnboundLocalError: local variable 'total' referenced before assignment
To prevent this error we either need to use 'global' keyword or global() function i.e.
total = 22 def func2(): global total if total > 10: total = 15
The Complete example of global variable and globals() in Python
# Global variable total = 100 def test(): # Local variable marks = 19 print('Marks = ', marks) print('Total = ', total) def func1(): total = 15 def func(): # refer to global variable 'total' inside function global total if total > 10: total = 15 def func2(): global total if total > 10: total = 15 def func3(): listOfGlobals = globals() listOfGlobals['total'] = 11 total = 22 print('Local Total = ', total) def main(): print('Total = ', total) func1() print('Total = ', total) func() print('Total = ', total) func2() print('Total = ', total) func3() print('Total = ', total) if __name__ == '__main__': main()
Output:
Total = 100 Total = 100 Total = 15 Total = 15 Local Total = 22 Total = 11
Related posts:
- Python : How to unpack list, tuple or dictionary to Function arguments using * & **
- Python : *args | How to pass multiple arguments to function ?
- Python : **kwargs | Functions that accept variable length key value pair as arguments
- Why do we need Lambda functions in Python ? | Explained with examples.
- Python : How to use if, else & elif in Lambda Functions
- Python : filter() function | Tutorial & Examples
- Python map() function – Tutorial
- Python : max() function explained with examples
- Python : min() function Tutorial with examples
- How to break out from multiple loops python?
- Return multiple values from a function in Python
- How to call a function every N seconds in Python?
- Python Functions
- Functions in Python
- Python : Different ways to Iterate over a List in Reverse Order
- Python : Sort a List of numbers in Descending or Ascending Order | list.sort() vs sorted()
- Python : How to Check if an item exists in list ? | Search by Value or Condition
- Python : Check if all elements in a List are same or matches a condition
- Python : Check if a list contains all the elements of another list
- Python : How to add an element in list ? | append() vs extend()
thank you. pulled my hair out over this, another irrational and bizarre python ‘feature’ this weekend.