![]() |
VOOZH | about |
In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to inspect or modify global variables dynamically during the execution of the program.
globals()
Return Value: The globals() function returns a dictionary where:
In this example, we are using the globals() function to display the global symbol table before any variables are defined as well as displaying the global symbol table after variables are defined.
Output
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},'__builtins__': <module 'builtins' (built-in)>}{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},'__builtins__': <module 'builtins' (built-in)>, 'p': 10, 'q': 100, 'r': 1000,'s':10000}
Explanation:
In this example, we are using globals() function to demonstrate about globals() function in Python.
15
Explanation: This code demonstrates how to modify a global variable inside a function using globals(). Initially, a = 5 is set globally. Inside the function, the local variables c and d are calculated, and the global variable a is updated to the value of d (15) using globals(). Finally, the updated value of a is printed.
In this example, we are using globals() to modify global variables in Python.
Before modification: Brijkant After modification: Brijkant Yadav
Explanation: This code demonstrates modifying a global variable using globals(). Initially, name = 'Brijkant' is set. Using globals()['name'] = 'Brijkant Yadav', the value of name is updated to 'Brijkant Yadav'. The updated value is then printed.