Python provides a large number of utility functions to perform various operations and the Python globals()
function is one such method. The globals()
method is a built-in function and it returns a dictionary of the current global symbol table.
globals() Syntax
The following is the syntax of the globals() method:
globals()
globals() Parameters
The globals()
method does not take any parameter as an argument.
globals() Return Value
The globals()
function returns a dictionary of the current global symbol table. This dictionary consists of all the global variables as well as other symbols for the current program that are stored in the current global symbol table.
What is a Symbol Table?
- Local symbol table: Local symbol table contains all the information related to the local scope of the program, and is accessed in Python using
locals()
method. A local scope can be within a function, within a class, etc. - Global symbol table: A Global symbol table contains all the information related to the global scope of the program, and is accessed in Python using
globals()
method. The global scope consists of all functions, variables that are not associated with any class or function.
globals() Examples
globals()
method can only access the global variables and not the local variable.# global variables
a = 5
b = 10
def myFunc():
# local variable
s = 100
print(globals())
Output:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'a': 5, 'b': 10, 'myFunc': <function myFunc at 0x7f034180ee50>}
Example 2:
Since the global symbol table stores all global variables, we can access and modify the value of a global variable using the globals()
function.
# global variables
a = 5
print("Before change the value of a is:",a)
globals()['a'] = 10
print("After change the value of a is:",a)
Output:
Before change the value of a is: 5
After change the value of a is: 10
In this way we have seen the working of the Python globals()
function and how it can be used to access the global variables and the global symbol table.