Table of Contents
The globals() method returns the dictionary of the current global symbol table.
A symbol table is a data structure maintained by a compiler which contains all necessary information about the program.
These include variable names, methods, classes, etc.
There are mainly two kinds of symbol table.
- Local symbol table
- Global symbol table
Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method.
The local scope could be within a function, within a class, etc.
Likewise, a Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals()
method.
The global scope contains all functions, variables that are not associated with any class or function.
Recommended Reading: Namespace and scope of in Python
1. Syntax of globals()
The globals table dictionary is the dictionary of the current module (inside a function, this is a module where it is defined, not the module where it is called).
The syntax of globals()
method is:
globals()
2. globals() Parameters
globals()
method doesn’t take any parameters.
3. Return value from globals()
globals()
method returns the dictionary of the current global symbol table.
4. Example 1: How globals() method works in Python?
globals()
Output
{'In': ['', 'globals()'], 'Out': {}, '_': '', '__': '', '___': '', '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '_dh': ['/home/repl'], '_i': '', '_i1': 'globals()', '_ih': ['', 'globals()'], '_ii': '', '_iii': '', '_oh': {}, '_sh': <module 'IPython.core.shadowns' from '/usr/local/lib/python3.5/dist-packages/IPython/core/shadowns.py'>, 'exit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>, 'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.core.interactiveshell.InteractiveShell object at 0x7fbc6478ee48>>, 'quit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>}
The output shows all global variables and other symbols for the current program.
5. Example 2: Modify global variable using global()
age = 23 globals()['age'] = 25 print('The age is:', age)
Output
The age is: 25
Here, since the global symbol table also stores all global variables, i.e. in this case, age, the value of age can be changed using globals()
function.
The dictionary returned is accessed using the key of the variable age and modified to 25.
This is reflected in the global symbol table again.