Python accessing global variables

Python — Global Variables

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example

Create a variable outside of a function, and use it inside the function

def myfunc():
print(«Python is » + x)

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Example

Create a variable inside a function, with the same name as the global variable

def myfunc():
x = «fantastic»
print(«Python is » + x)

The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example

If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = «fantastic»

Also, use the global keyword if you want to change a global variable inside a function.

Example

To change the value of a global variable inside a function, refer to the variable by using the global keyword:

def myfunc():
global x
x = «fantastic»

Источник

Python Global Variables

In this tutorial, you’ll learn what is a global variable in Python and how to use them effectively.

Goals of this lesson:

  • Understand what is a global variable in Python with examples
  • Use global variables across multiple functions
  • Learn how to use the global keyword to modify the global variables
  • Learn to use global variables across Python modules/files
  • Understand the use of globals() function
  • Use global variables inside a nested function

Table of contents

What is a Global Variable in Python

In Python, a variable declared outside the function or in global scope is known as a global variable. We can use global variables both inside and outside the function.

The scope of a global variable is broad. It is accessible in all functions of the same module.

Python global variables

Let’s understand it with an example.

In this example, we declared a global variable name with the value ‘Jessa’. The same global variable name is accessible to everyone, both inside of functions and outside.

# global variable name = 'Jessa' def my_func(): # access global variable inside function print("Name inside function:", name) my_func() # access global variable outside function print('Name Outside function:', name)
Name inside function: Jessa Name Outside function: Jessa

Using Global Variables In Function

We can use global variables across multiple functions of the same module.

Now, let’s see how to use the global variable inside a Python function.

  • First, create a global variable x and initialize it to 20. The same global variable x is accessible to everyone, both inside of functions and outside.
  • Now, create a function with a combination of local variables and global variables.
  • Create a local variable y And initialize it to 30. A local variable is declared inside the function and is not accessible from outside it. The local variable’s scope is limited to that function only where it is declared.
  • In the end, add a global variable x and local variable y to calculate the sum of two variables.
# global variable x = 20 def add(): # local variable y y = 30 print('local variable y=', y) # Use global variable x print('global variable x=', x) z = x + y print('x+y=', z) def sub(): # local variable m m = 10 print('local variable m=', m) # Use global variable x in second function print('global variable x=', x) n = x - m print('x-m=', n) add() sub()
local variable y= 30 global variable x= 20 x+y= 50 local variable m= 10 global variable x= 20 x-m= 10

Global Variable and Local Variable with Same Name

Note: If you create a new local variable inside a function with the same name as a global variable, it will not override the value of a global variable. Instead, the new variable will be local and can only be used inside the function. The global variable with the same name will remain unchanged.

# global variable x = 20 def my_func(): # local variable with same name # it will not change global variable x x = 50 print('local variable x=', x) # modify local variable x x = 100 print('local variable x=', x) my_func() print('Global variable x=', x) 
local variable x= 50 local variable x= 100 Global variable x= 20

global Keyword in Python

The global keyword is used in the following two cases.

  • To access and modify a global variable inside a function
  • To create a new global variable inside a function

Modify a global variable inside a function

# global variable x = 20 def my_func(): # modify global variable x x = x + 30 my_func()
UnboundLocalError: local variable 'x' referenced before assignment

Execute the above code to change the global variable x’s value. You’ll get an UnboundLocalError because Python treats x as a local variable, and x is also not defined inside my_func(). i.e, You cannot change or reassign value to a global variable inside a function just like this.

Use the global keyword to change the value of a global variable inside a function.

# global variable x = 20 def my_func(): # modify global variable x using global keyword global x x = x + 30 print('global variable x inside a function:', x) # Value of global variable before calling a function print('global variable x outside a function:', x) # Value of global variable after calling a function my_func() print('global variable x outside a function:', x)
global variable x outside a function: 20 global variable x inside a function: 50 global variable x outside a function: 50

Create a global variable inside a function

in Python, the scope of variables created inside a function is limited to that function. We cannot access the local variables from outside of the function. Because the scope is local, those variables are not visible outside the function.

To overcome this limitation, we can use the global keyword to create a global variable inside a function. This global variable is accessible within and outside the function.

def my_func(): # create new global variable x using global keyword global x x = 100 print('global variable x inside a function:', x) my_func() print('global variable x outside a function:', x)
global variable x inside a function: 100 global variable x outside a function: 100

Rules of global keyword

Let us see the rules we need to follow to create and use a global keyword.

  • If we create a variable inside a function, it is a local variable by default.
  • If we create a variable outside the function, it turns into a global variable, and we don’t have to use the keyword global.
  • We use the keyword global to create a global variable inside a function or to change a global variable already declared outside the function.
  • Using the global keyword outside the function does not make any difference.

Global Variables Across Python Modules/Files

By default, the global variables are accessible across multiple functions of the same module. Now, we’ll see how to share global variables across the modules.

  • First, create a special module config.py and create global variables in it.
  • Now, import the config module in all application modules, then the module becomes available for a global name.

Let us understand it using an example.

In Python, to create a module, write Python code in the file, and save that file with the .py extension.

Example: Share global variables across Python modules.

config.py : The config module stores global variables of school and grade

# global variables company_name = 'ABC Company' address = 'XYZ street, New York'

Now, run the config.py file.

company.py : create a company.py file to import global variables and modify them. In the company.py file, we import the config.py module and modify the values of the name and address.

# load config module import config # modify global variables config.company_name = 'ABC Tech' config.address = "New Street, california" 

Now, run the company.py file.

Now, in the employee file, we import both config and company modules to test the values of global variables and whether they are changed.

# load config and company module import config import company print('Company Name:', config.company_name) print('Address:', config.address)
Company Name: ABC Tech
Address: New Street, california

As you can see in the output, we successfully accessed and modified the global variables across the files or modules.

globals() function in Python

In this section, we’ll see what the globals() do in Python.

We can also use the globals() function to access and modify the global variables. The globals() function returns the dictionary of the current global symbol table.

The global symbol table stores all information related to the program’s global scope and is accessed using the globals() method.

Function and variables are not part of any class, or functions are stored in a global symbol table.

Example: Modify the global variable using the globals() function.

# global variable z = 20 def add(): x = 30 y = 20 # change value of global variable using globals() globals()['z'] = x + y print('Global variable before calling function:', z) add() print('Global variable after calling function:', z)
Global variable before calling function: 20 Global variable after calling function: 50

Global variables in Nested Function

Now, Let’s see how to use a global variable in a nested function. Global variables can be used in a nested function using global or nonlocal keywords.

The difference between nonlocal and global is that global is used to change global variables, while nonlocal is used to change variables outside the function. Let us illustrate this with an example.

Example: Access global variables in nested functions using the global keyword

# global variable a = 10 def outer_fun(): b = 20 def inner_fun(): c = 30 # access outer function variable using nonlocal nonlocal b # access global variable using global global a # add them a = b + c # call inner function inner_fun() print('Global variable before calling nested function:', a) outer_fun() print('Global variable after calling nested function:', a) 
Global variable before calling nested function: 10 Global variable after calling nested function: 50

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Читайте также:  Previous posts link php
Оцените статью