Global Variables in Python

Filed Under: Python
Python Global Variables

In this tutorial, We will look into Python Global Variables. We will learn how to define a global variable and then how to access them in a function.

Global Variables in Python

Global Variables are defined outside a function. We can access a global variable in all parts of the Python program.

Python Global Variables Example

Let’s look at a simple example to declare a global variable. Then we will use this global variable in a function.

website = "JournalDev.com"


def return_website():
    return website


print(f'My favorite website is {return_website()}')

Output:

My favorite website is JournalDev.com

The variable “website” is defined in the program, outside of a function. So, it becomes a global variable.

Using global keyword to access global variable

If there is a variable defined inside a function with the same name, then we have to use global keyword to access the global variable. Otherwise, the local variable value will be used.

Let’s look at a quick example to use the global keyword to access global variables.

website = "JournalDev.com"


def print_website():
    global website
    print(f'My favorite website is {website}')

    website = 'Wikipedia.com'
    print(f'My favorite website is {website}')


print_website()

Output:

My favorite website is JournalDev.com
My favorite website is Wikipedia.com

If we don’t use the global keyword, the program will throw error message “UnboundLocalError: local variable referenced before assignment”.

The best practice is to avoid using the same name as the global variable and stay away from the name conflicts.

Quick word on Python globals() function

Python globals() function return a dictionary representing the current global symbol table. This dictionary contains the global variables name and its values. We can use this function to get quick information on all the global variables.

Python program maintains program information in symbol tables.

There are two types of symbol tables:

  1. Local Symbol Table – stores information related to the local scope of the program.
  2. Global Symbol Table – stores information related to global scope of the program.

Python symbol table contains details about variable names, methods, classes, etc.

Python globals() function doesn’t accept any arguments.

print(globals())

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a99b358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_globals_example.py', '__cached__': None}

It also prints the python script from where this function is called.

Let’s see the output if the same function is called from the Python interpreter.

$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> 

This time there is no __file__ attribute in the output.

Global Variables in globals() dictionary

As we mentioned earlier that the global symbol table contains information about the global variables.

Let’s see this with a simple example.

name = 'Pankaj'

print(globals())

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a99b358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_globals_example.py', '__cached__': None, 'name': 'Pankaj'}

The global symbol dictionary contains the ‘name’ variable too.

One of the features of globals() is that we can modify the variables in the global dictionary. Since it’s a dictionary, we can get the value of a specific key too.

globals()['name'] = 'David'

print(globals()['name'])

Output: David

Let’s see if globals() contains local scope variables or not. For this, let’s define a function and some variables inside it.

def fx():
    local = ''
    global gl
    gl = 'Global'


fx()  # calling fx() to set the variables
print(globals())

print(globals()['gl'])

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a99b358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_globals_example.py', '__cached__': None, 'name': 'David', 'fx': <function fx at 0x10a9331e0>, 'gl': 'Global'}

Global

The ‘gl’ variable is part of the global dictionary because its scope is global. Whereas, ‘local’ variable is not part of the global dictionary because of having local scope.

Conclusion

Python global variables are very easy to define and use. The globals() function returns the global variables and it can be used in debugging the code. We can use it to identify the global scope variables and functions available to the program. We can also modify the global variable data, but that is not advisable and mostly not required in normal programs.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages