Summary: Use the
global keyword to declare a global variable inside the local scope of a function so that it can be modified or used outside the function as well. To use global variables across modules create a special configuration module and import the module into our main program. The module is available as a global name in our program. As each module has a single instance, any changes to the module object get reflected everywhere.
Problem: Given a function; how to use a global variable in it?
def foo(): # Some syntax to declare the GLOBAL VARIABLE "x" x = 25 # Assigning the value to the global variable "x" def func(): # Accessing global variable defined in foo() y = x+25 print("x=",x,"y=",y) foo() func()
x= 25 y= 50
In the above example, we have been given a function named
foo() which returns a global variable
x such that the value of
x can be used inside another function named
func(). Let us have a quick look at how we can use the
global keyword to resolve our problem.
Solution: Using The Global Keyword
We can use the
global as a prefix to any variable in order to make it global inside a local scope.
def foo(): global x x = 25 def func(): y = x+25 print("x=",x,"y=",y) foo() func()
x= 25 y= 50
Now that we already know our solution, we must go through some of the basic concepts required for a solid understanding of our solution. So, without further delay let us discuss them one by one.
Variable Scope In Python
The scope of a variable is the region or part of the program where the variable can be accessed directly. Let us discuss the different variable scopes available in Python.
❖ Local Scope
When a variable is created inside a function, it is only available within the scope of that function and ceases to exist if used outside the function. Thus the variable belongs to the local scope of the function.
def foo(): scope = "local" print(scope) foo()
❖ Enclosing Scope
An enclosing scope occurs when we have nested functions. When the variable is in the scope of the outside function, it means that the variable is in the enclosing scope of the function. Therefore, the variable is visible within the scope of the inner and outer functions.
def foo(): scope = "enclosed" def func(): print(scope) func() foo()
In the above example, the variable
scope is inside the enclosing scope of the function
foo() and available inside the
foo() as well as
❖ Global Scope
A global variable is a variable that is declared in a global scope and can be used across the entire program; that means it can be accessed inside as well outside the scope of a function. A global variable is generally declared outside functions, in the main body of the Python code.
name = "FINXTER" def foo(): print("Name inside foo() is ", name) foo() print("Name outside foo() is :", name)
Name inside foo() is FINXTER Name outside foo() is : FINXTER
In the above example,
name is a global variable that can be accessed inside as well as outside the scope of the function foo(). Let’s check what happens if you try to change the value of the global variable
name inside the function.
name = "FINXTER" def foo(): name = name + "PYTHON" print("Name inside foo() is ", name) foo()
Traceback (most recent call last): File "main.py", line 8, in <module> foo() File "main.py", line 4, in foo name = name + "PYTHON" UnboundLocalError: local variable 'name' referenced before assignment
We get an
UnboundLocalError in this case, because Python treats
name as a local variable inside
name is not defined inside
foo(). If you want to learn more about the UnboundLocalError and how to resolve it, please read it in our blog tutorial here.
❖ Built-In Scope
The built-in scope is the widest scope available in python and contains keywords, functions, exceptions, and other attributes that are built into Python. Names in the built-in scope are available all across the python program. It is loaded automatically at time of executing a Python program/script.
x = 25 print(id(x))
In the above example, we did not import any module to use the functions
id(). This is because both of them are in the built-in scope.
Having discussed the variable scopes in Python, let us discuss about a couple of very important keywords in Python in relation to the variable scopes.
Use Global Variables Inside A Function Using The global Keyword
We already read about the global scope where we learned that every variable that is declared in the main body and outside any function in the Python code is global by default. However, if we have a situation where we need to declare a global variable inside a function as in the problem statement of this article, then the global keyword comes to our rescue. We use the
global keyword inside a function to make a variable global within the local scope. This means that the global keyword allows us to modify and use a variable outside the scope of the function within which it has been defined.
Now let us have a look at the following program to understand the usage of the
def foo(): global name name = "PYTHON!" print("Name inside foo() is ", name) foo() name = "FINXTER "+name print("Name outside foo() is ", name)
Name inside foo() is PYTHON! Name outside foo() is FINXTER PYTHON!
In the above example, we have a global variable name declared inside the local scope of function foo(). We can access and modify this variable outside the scope of this variable as seen in the above example.
❃ POINTS TO REMEMBER
- A variable defined outside a function is global by default.
- To define a global variable inside a function we use the
- A variable inside a function without the
globalkeyword is local by default.
- Using the
globalkeyword for a variable that is already in the global scope, i.e., outside the function has no effect on the variable.
Global Variables Across Modules
In order to share information across Python modules within the same piece of code, we need to create a special configuration module, known as config or cfg module. We have to import this module into our program. The module is then available as a global name in our program. Because each module has a single instance, any changes to the module object get reflected everywhere.
Let us have a look at the following example to understand how we can share global variables across modules.
Step 1: config.py file is used to store the global variables.
Step 2: modify.py file is used to change global variables.
Step 3: main.py file is used to apply and use the changed values of the global variable.
Output After Executing
The nonlocal Keyword
nonlocal keyword is useful when we have a nested function, i.e., functions having variables in the enclosing scope. In other words if you want to change/modify a variable that is in the scope of the enclosing function (outer function), then you can use the
def foo(): a = 25 print("Value of 'a' before calling func = ",a) def func(): nonlocal a a=a+20 print("Value of 'a' inside func = ",a) func() print("Value of 'a' after exiting func = ",a) foo()
Value of 'a' before calling func = 25 Value of 'a' inside func = 45 Value of 'a' after exiting func = 45
From the above example it is clear that if we change the value of a
nonlocal variable the value of the
local variable also changes.
The key points that we learned in this article are:
- Variable Scopes:
- Local Scope
- Enclosing Scope
- Global Scope
- Built-in Scope
- Important Keywords:
- How to use a global variable inside a function?
- How to use a global variable across modules?
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.