Tutorial Study Image

Python globals()

The function globals() returns a dictionary of the global symbol table. The symbol table is a data structure that holds the details of occurrences of variables, functions, objects, classes, and it is handled by the compiler. Symbol tables are of two types Local symbol table and Global symbol table.

The Local symbol table contains the local information of the program it means within a function, within a class, etc. The Global symbol table contains details about the global scope of the program it means details of all functions and classes.


globals()
 

globals() Parameters:

globals() method doesn't take any parameters.

globals() Return Value

globals() method returns the dictionary of the current global symbol table. The dictionary contains global variables such as filename, package, or docstring from the current global symbol table.

Examples of globals() method in Python

Example 1: How globals() method works in Python?


globals()
 

Output:

{'In': ['', 'globals()'],
 'Out': {},
 '_': '',
 '__': '',
 '___': '',
 '__builtin__': ,
 '__builtins__': ,
 '__name__': '__main__',
 '_dh': ['/home/repl'],
 '_i': '',
 '_i1': 'globals()',
 '_ih': ['', 'globals()'],
 '_ii': '',
 '_iii': '',
 '_oh': {},
 '_sh': ,
 'exit': ,  'get_ipython': >,
 'quit': }

Example 2: Modify global variable using global()


age = 23

globals()['age'] = 25
print('The age is:', age)
 

Output:

The age is: 25