globals() Built-in Function
Python - globals()
Python globals() built-in function is used to get the global symbol table as a dictionary.
In this tutorial, you will learn the syntax and usage of globals() built-in function with examples.
Syntax
The syntax of globals() function is
globals()
Examples
1. Get value of a global variable in a function
In the following program, we define a variable x
in global scope, and a variable x
in a function my_function
. By default we can access the value in x
using the variable x
. After that, you will see how to access the value in global variable x
.
Python Program
x = 10
def my_function():
x = 20
print("x [local value] :", x)
# Print value in global x
print("x [global value] :", globals()['x'])
my_function()
Output
x [local value] : 20
x [global value] : 10
2. Print all global variables
In the following program, we print the dictionary returned by the globals() built-in function.
Python Program
x = 10
def my_function():
x = 20
print(globals())
my_function()
Output
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x102790ca0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pythonexamples/Desktop/Desktop - PYTHONEXAMPLES_ORG’s Mac mini - 1/Projects/PythonTutorial/main.py', '__cached__': None, 'x': 10, 'my_function': <function my_function at 0x1026cfeb0>}
Summary
In this Built-in Functions tutorial, we learned the syntax of the globals() built-in function, and how to use this function to access the values of global variables.