Function Name:
globals
Function Signature:
globals()
Function Overview:
- The function globals() returns the module level symbol table as a dictionary instance.
- The symbol table in python is a collection of names and their values as defined in a scope. Scope could be global-module level or local - function level.
- The module level symbol table in Python contains the following:
- Module level attributes e.g., __name__, __package__
- Classes defined in the module
- Functions defined in the module
- Constants and Variables declared in the module
- Unlike the dictionary returned by the locals() method, the dictionary returned by the globals() method is not a copy of the module level symbol table.
- It is the module level symbol table itself. Hence any changes made to this dictionary are reflected in the program.
Example1:
def A(x): y = 0 z = x localNames = locals() print(localNames)
A(1) print(globals()) |
Output:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1006ba320>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'globalsex.py', '__cached__': None, 'A': <function A at 0x100662e18>} |
Example2:
inflation = 1.5
print("Inflation is :{}".format(inflation))
symbolTable_Module = globals()
# Change the inflation variable through symbol table symbolTable_Module["inflation"] = 1.6
# Check the changes made to the dictionary are reflecting in the program print("Inflation is :{}".format(inflation))
|
Output:
Inflation is :1.5 Inflation is :1.6 |