Python provides a variety of built-in functions that are useful for developers to manipulate and manage variables, modules, and other objects. One such function is "globals()", which allows you to access all the global variables that are currently defined in the current module. In this article, we will explore the "globals()" function, its syntax, and its usage with the help of examples.
The "globals()" function is a built-in function in Python that returns a dictionary object representing the current global symbol table. This dictionary contains all the global variables, functions, and classes that are currently defined in the current module. The syntax for using the "globals()" function is as follows:
globals()When you call the "globals()" function, it returns a dictionary object containing all the global variables in the current module. The keys of the dictionary are the variable names, and the values are the values of the variables. The returned dictionary is not a copy of the global namespace, but a reference to the actual global namespace.
Let's take a look at some examples to understand how to use the "globals()" function.
Example 1: Accessing Global Variables
|
# define some global variables
name = "John"
age = 30
# get all global variables
all_globals = globals()
# print the value of the global variables
print(all_globals["name"])
print(all_globals["age"])
|
John 30Example 2: Updating a Global Variable
|
# define a global variable
value = 10
# get all global variables
all_globals = globals()
# update the value of a global variable
all_globals["value"] = 20
# print the updated value of the global variable
print(value)
|
In this example, we define a global variable "value" with the initial value of 10. We then call the "globals()" function, which returns a dictionary object containing all the global variables in the current module. We then update the value of the "value" variable in the dictionary returned by "globals()" to 20. Finally, we print the updated value of the "value" variable, which should be 20. The output of this code will be:
20Example 3: Using Globals() in a Function
|
# define a global variable
name = "John"
# define a function that uses the global variable
def say_hello():
global name
print("Hello, " + name + "!")
# get all global variables
all_globals = globals()
# call the function
say_hello()
|
n this example, we define a global variable "name" with the value "John". We then define a function "say_hello()" that uses the global variable "name" to print a greeting message. Inside the function, we use the "global" keyword to tell Python that we want to access the global variable "name". We then call the "globals()" function to get all the global variables in the current module. Finally, we call the "say_hello()" function, which uses the global variable "name" to print the greeting message. The output of this code will be:
Hello, John!