What is Python globals()?

Python globals() is a built-in function which is used to obtain a dictionary that holds the current global symbol table of the module you are working in or the global namespace of the script. With this function, you gain access to all the global variables, functions, and classes defined within the current module or at the top level of your script. This way, you can conveniently inspect and work with the global elements defined in your code.

Before delving into practical applications of the Python globals(), it is essential to grasp its syntax as it hold significant importance in executing the examples. Familiarizing yourself with this aspect will enable you to make the most of this function in various scenarios.

Python globals() Syntax and Parameter

The syntax of the Python globals() function is quite simple, making it easy to use in your code. To access it, you simply need to call the globals() function without any arguments. Here’s the basic syntax:

globals()

Above, you can observe the straightforward nature of using the globals() function. Unlike several other Python functions, you don’t need to provide any parameters or arguments when you call globals(). It will promptly return the global symbol dictionary as a dictionary object.

Now that you have acquired a solid understanding of the function’s purpose and syntax it’s time to explore its return value and witness Python globals() in action!

Python globals() Return Value

When you use the globals() function, it returns you a dictionary representing the current global symbol dictionary in Python. Inside this dictionary, you can find all the global variables along with their corresponding values, which are defined in the current module. Let’s explore a straightforward example that showcase the return value of the globals() function:

Example Code
global_var = "I am a global variable" another_global_var = 42 print("Global variables in the module:", globals())

For this example, we have defined two global variables using the assignment statements. The first variable global_var is a string with the value I am a global variable, and the second variable another_global_var is an integer with the value 42. To examine the current global symbol dictionary, we use the globals() function, which returns a dictionary containing all the global variables, functions, and classes defined in the current module.

We then use the print() function to display the output. The output will show the global variables in the module along with their corresponding values. In this case, it will print:

Output
Global variables in the module: {‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <_frozen_importlib_external.SourceFileLoader object at 0x00000282CEE247C0>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘__file__’: ‘C:\\Users\\sexy inayat\\Desktop\\Python mrxmodule\\1.py’, ‘__cached__’: None, ‘global_var’: ‘I am a global variable’, ‘another_global_var’: 42}

As you can see in the above example, that this approach allows you to inspect and work with the global variables effectively.

As we discussed before, the globals() function serves as a means to access global variables, functions, and other elements. To fully comprehend its capabilities, let’s delve into practical examples. Through this exploration, you will gain a concrete understanding of how this function operates in real-world situations. So, let’s embark on this journey and uncover the boundless potential of globals()!

I. Creating a globals() Object

Unlike many Python functions that create new objects with specific values, the globals() function does not create a new object. Instead, it allows direct access to an existing object, which is the global symbol dictionary. However, it’s important to note that if you attempt to create an object using the globals() function, it will result in an error. Let’s explore an example that illustrate the error that occurs when trying to create an object using globals().

Example Code
try: obj = globals() except TypeError as e: print(f"Error: {e}")

Here, we try to assign the result of calling globals() to a variable obj. However, since globals() is not callable, it raises a TypeError. We catch this error in the except block and print an error message showing the type of exception raised.

Output
Error: ‘dict’ object is not callable

This is because globals() is a dictionary, and dictionaries are not callable, so trying to call it like a function will result in a TypeError.

II. Python globals() with Global Variables

The Python globals() function enables you to interact with global variables within a function or any relevant scope. When you use globals(), you gain access to a dictionary that allows you to read, modify, or delete global variables directly. It provides a convenient way to handle global variable operations, such as accessing their values, making changes, or removing them entirely. Here’s a brief explanation of what you can do with globals():

A. Access Global Variables

You can use globals() to retrieve the value of a global variable from anywhere within your code, even inside functions or nested scopes. For example:

Example Code
global_var1 = "This way I access variable" global_var2 = 123 def access_global_variables(): print("Inside the function:") print("global_var1:", global_var1) print("global_var2:", global_var2) access_global_variables() print("Outside the function:") print("global_var1:", global_var1) print("global_var2:", global_var2)

In this example, we have two global variables named global_var1 and global_var2. Then we set the values of these variables to This way I access variable and 123, respectively.

We then define a function called access_global_variables(), which allows us to access and print the global variables. Inside the function, we use the print() function to display the values of global_var1 and global_var2 along with corresponding messages. This way, we can see the values of the global variables when the function is called.

After defining the function, we call access_global_variables() to execute it. This will print the values of global_var1 and global_var2 inside the function, which will be This way I access variable and 123, respectively.

Next, we move outside the function, and we once again use the print() function to display the values of the global variables. This time, we are outside the function’s scope, but we can still access and print the same global variables. So, when we print the values of global_var1 and global_var2 outside the function, we will get the same values as before.

Output
Inside the function:
global_var1: This way I access variable
global_var2: 123
Outside the function:
global_var1: This way I access variable
global_var2: 123

Thus, the example showcase that global variables can be accessed and used both inside and outside a function in Python.

B. Modify Global Variables

To change the value of a global variable, you can directly modify the corresponding key-value pair in the dictionary returned by globals(). Consider the following example:

Example Code
text1 = "Before modification variable" def modify_global_variables(): global text1 text1 = "After modification variable" print("Before modification:") print("text1:", text1) modify_global_variables() print("After modification:") print("text1:", text1)

For this example, we have a global variable named text1. After this we set its initial value to Before modification variable. We define a function called modify_global_variables(), where we use the global keyword to indicate that we want to modify the global variable text1. Inside the function, we change the value of text1 to After modification variable. Before calling the function, we print the value of text1 to see its initial state.

Next, we call the function modify_global_variables() to modify the value of text1. After the function call, we print the value of text1 again to see the changes.

Output
Before modification:
text1: Before modification variable
After modification:
text1: After modification variable

Therefore, the code illustrates the process of altering a global variable within a function and witnessing the changes that occur both before and after the modification.

C. Delete Global Variables

To completely remove a global variable, you can utilize the del statement on the relevant key in the globals() dictionary. For example:

Example Code
car_name = "Tesla Model S" car_year = 2022 def delete_car_variables(): global car_name, car_year del car_name del car_year print("Before deletion:") print("Car Name:", car_name) print("Car Year:", car_year) delete_car_variables() print("\n") print("After deletion:") print("Car Name is deleted") print("Car Year is deleted")

Here, we have two global variables named car_name and car_year. Initially, car_name is set to Tesla Model S, and car_year is set to 2022. We define a function called delete_car_variables(), where we use the global keyword to indicate that we want to modify the global variables car_name and car_year.

Inside the function, we use the del statement to delete both car_name and car_year. This means we are removing these variables entirely from the global scope. Before calling the function, we print the values of car_name and car_year to see their initial state.

Next, we call the function delete_car_variables() to delete the global variables car_name and car_year. After calling the function, we print the message After deletion: and indicate that both Car Name and Car Year are deleted. This is because attempting to access these variables outside the function will raise a NameError since they no longer exist in the global scope.

Output
Car Name: Tesla Model S
Car Year: 2022


After deletion:
Car Name is deleted
Car Year is deleted

Hence, the code exemplifies the deletion of global variables using the del statement and confirms their absence from the global scope after the deletion process.

III. The globals(): Insights into the Current Module

Python globals() provides valuable insights into the current module’s global symbol table. You can list all the global variable names and even access their values dynamically. This can be particularly useful when you have a large number of global variables or when you need to interact with them dynamically during runtime. For instance:

Example Code
name = "Tom" location = "New York" def print_globals(): all_globals = globals() for name, value in all_globals.items(): print(f"{name}: {value}") print_globals()

In this example, we have two global variables named name and location. The variable name is set to Tom, and location is set to New York. We define a function called print_globals(), where we first use globals() to obtain a dictionary containing all the global variables and their respective values in the current module.

Inside the function, we use a for loop to iterate through the all_globals dictionary. For each item in the dictionary, we print the variable name and its corresponding value using the print() function. When we call the print_globals() function, it will display the output, listing all the global variables and their values:

Output
__name__: __main__
__doc__: None
__package__: None
__loader__: <_frozen_importlib_external.SourceFileLoader object at 0x000001E5D30247C0>
__spec__: None
__annotations__: {}
__builtins__: <module ‘builtins’ (built-in)>
__file__: C:\Users\sexy inayat\Desktop\Python mrxmodule\1.py
__cached__: None
name: Tom
location: New York
print_globals:

As you can see in the above example, you can easily use globals() to access and print all the global variables along with their respective values within the current module.

IV. Python globals() with Conditional Statements

By employing the globals() function in Python alongside conditional statements, you can dynamically access and manipulate global variables based on certain conditions. Here’s an example that showcase this concept:

Example Code
global_var = "I am a Conditional Statement" def check_and_update_global(): global global_var if global_var == "I am a Conditional Statement": global_var = "Updated global variable" else: print("Sorry, can't update the value") print("Before update:") print("global_var:", global_var) check_and_update_global() # After update print("After update:") print("global_var:", global_var)

Here, we have a global variable named global_var initially set to I am a Conditional Statement. We define a function called check_and_update_global(). Within the function, we utilize the global keyword to signify our intention of modifying the global variable global_var.

Within the function, we have a conditional statement (if global_var == "I am a Conditional Statement":) that checks whether the value of global_var is I am a Conditional Statement. If the condition is true, we update the value of global_var to Updated global variable. If the condition is false, indicating that global_var does not match the expected value, the else block is executed, and it prints Sorry, can't update the value. Before calling the function, we print the value of global_var to see its initial state.

Output
Before update:
global_var: I am a Conditional Statement
After update:
global_var: Updated global variable

By using this approach you can use a conditional statement to check the value of a global variable and then modify it accordingly.

Python globals() Advanced Examples

In below section, we will explore some advanced illustrations of the Python globals() to showcase its flexibility and diverse applications.

I. Python globals() with Lists

Python globals() enables you to access and interact with lists when they are defined as global variables. By using globals(), you gain entry to the global symbol table containing list variables and their respective values. Here’s a concise explanation of its capabilities with lists:

  • Access: Read list elements directly from the global variables.
  • Modify: Update list elements directly through the function.
  • Delete: Remove elements from the list as needed.

Overall, the globals() function efficiently manages and interacts with global list variables, proving particularly valuable for dynamic manipulation of list data during runtime and across various parts of the code. Consider a following example through which you will get a clear picture of how globals() works with list.

Example Code
my_global_list = [1, 2, 3, 4, 5] def modify_list(): # Accessing the global list using globals() global_list = globals()["my_global_list"] # Modifying the list elements directly global_list[2] = 10 global_list.append(6) print("Before modification:") print("my_global_list:", my_global_list) modify_list() print("After modification:") print("my_global_list:", my_global_list)

In this example, we have a global list variable named my_global_list, initially containing the elements [1, 2, 3, 4, 5]. The function modify_list() illustrates how to access and modify the global list. Inside the function, we use globals() to access the global symbol table and retrieve the my_global_list variable. Then, we directly modify the list elements by setting global_list[2] to 10 and appending the value 6 to the list.

Before calling the function, we print the initial state of my_global_list. After calling the function, we see that the global list has been modified as shown in the output.

Output
Before modification:
my_global_list: [1, 2, 3, 4, 5]
After modification:
my_global_list: [1, 2, 10, 4, 5, 6]

This example illustrates how to utilize the globals() function to work with global list variables efficiently, making it easy to read, modify, or delete list elements directly.

II. Python globals() with Tuples

When you use globals() with tuples, similar to lists, you gain the ability to access, modify, and delete tuple variables from the global scope. It allows you to directly read the elements of the tuples, update the tuple values, or remove the tuple variables altogether.

Python globals() provides a convenient way to interact with global tuple variables, just like its behavior with lists, during runtime or across different parts of your code. This dynamic manipulation of tuples can be particularly useful in various programming scenarios, making your code more flexible and adaptable. For example:

Example Code
coordinates = (10, 20) def update_coordinates(x, y): global coordinates coordinates = (x, y) print("The coordinates before modification are: ",coordinates) update_coordinates(15, 25) print("The coordinates after modification are:",coordinates)

Here, we have a tuple named coordinates initially set to (10, 20). We define a function called update_coordinates(x, y). Inside the function, we use the global keyword to indicate that we want to modify the global variable coordinates. The function takes two arguments x and y, and we assign the new values of x and y to the coordinates tuple, effectively updating it. Before calling the function, we print the initial state of coordinates using the print() function.

Output
The coordinates before modification are: (10, 20)
The coordinates after modification are: (15, 25)

As you can observed, how you can use a function with the global keyword to modify a global tuple variable coordinates and observe the changes before and after the update.

III. Difference between globals() and locals()

In Python, both globals() and locals() are built-in functions that allow you to access the symbol tables for global and local variables, respectively. However, there are significant differences between these two functions: Consider the following scenarios through which you will understand the main difference between locals() and globals() functionalities:

A. Python globals() Function

As previously explained, the globals() function is a convenient tool used to access global variables. To better comprehend its functionality compared to locals(), let’s explore an example that illustrates how globals() works in contrast to locals().

Example Code
odd_num1 = 3 odd_num2 = 7 odd_num3 = 11 def modify_global_odd_numbers(): global_dict = globals() global_dict["odd_num1"] = 5 global_dict["odd_num2"] = 9 global_dict["odd_num3"] = 13 print("odd_num1:", odd_num1) print("odd_num2:", odd_num2) print("odd_num3:", odd_num3) modify_global_odd_numbers() print("\n\nAfter changes in odd number:") print("odd_num1:", odd_num1) print("odd_num2:", odd_num2) print("odd_num3:", odd_num3)

Here, we have three global variables: odd_num1, odd_num2, and odd_num3, initially set to the odd numbers 3, 7, and 11, respectively. We define a function called modify_global_odd_numbers(). Inside the function, we use globals() to retrieve the global symbol table as a dictionary, which allows us to directly access and modify the values of the global variables.

Inside the function, we modify the odd numbers by updating the values of odd_num1, odd_num2, and odd_num3 to 5, 9, and 13, respectively. Before calling the function, we print the initial values of the odd numbers using the print() function.

Next, we call the modify_global_odd_numbers() function. As a result, the values of odd_num1, odd_num2, and odd_num3 are updated inside the function. After calling the function, we print the updated values of the odd numbers to observe the changes.

Output
odd_num1: 3
odd_num2: 7
odd_num3: 11

After changes in odd number:
odd_num1: 5
odd_num2: 9
odd_num3: 13

This example showcase how globals() can efficiently modify global variables containing odd numbers, allowing direct alterations within the global scope across the entire code.

B. Python locals() Function

On the other hand, If you use locals() function then it returns a dictionary representing the current local symbol table. It provides access to all the local variables defined within the current scope, such as inside a function or a block. The keys of the dictionary are the variable names, and the values are the corresponding variable values. You can use this function to introspect the local variables and their values, but it is important to note that modifying the locals() dictionary does not affect the actual variables in the local scope. For instance:

Example Code
def famous_places(): city = "Paris" landmark = "Eiffel Tower" population = 2150893 language = "French" local_vars = locals() print("Famous place in", city, ":") print("Landmark:", local_vars["landmark"]) print("Population:", local_vars["population"]) print("Official language:", local_vars["language"]) famous_places()

In this example, we have a function called famous_places(), which represents a place named Paris. Inside the function, we define several local variables such as city, landmark, population, and language.

The locals() function is used to access the local symbol table of the function and returns a dictionary containing the local variables along with their values. We use locals() to access the values of the local variables landmark, population, and language, and then we print them along with the city's name.

Output
Famous place in Paris :
Landmark: Eiffel Tower
Population: 2150893
Official language: French

By using this above approach you can efficiently access and display the values of local variables, making it easier to work with data within a specific function scope, such as famous places in this example.

IV. Handling Exceptions and Errors with globals()

Using globals() to handle exceptions and errors allows you to access and manipulate global variables within the scope of an exception block. When an exception is raised, the globals() function provides a means to examine and possibly modify global variables to handle the error or exception more flexibly. This can be valuable for debugging and understanding the cause of the error. For example:

Example Code
def get_global_variable(var_name): try: return globals()[var_name] except KeyError: return f"Variable '{var_name}' does not exist." # Get the value of a global variable print(get_global_variable("celebrity")) print(get_global_variable("city"))

Here, we have defined a function called get_global_variable(var_name) which allows us to access the values of global variables dynamically.

Inside the function, we use a try-except block to handle possible errors. When the function is called with the name of a global variable as an argument (e.g., "celebrity" or "city"), it attempts to retrieve the value of that variable using the globals() function. If the specified global variable exists, the function returns its value. However, if the variable does not exist in the global symbol table, a KeyError is raised in the try block. We handle this exception in the except block, and the function returns a string stating that the variable with the given name does not exist.

Output
Variable ‘celebrity’ does not exist.
Variable ‘city’ does not exist.

This way, you can use the get_global_variable() function to dynamically access global variables while gracefully handling potential errors for non-existent variables.

V. Synergizing globals() with Other Python Functions and Tools

You can combine the globals() function with other Python functions and tools to perform various tasks, including dynamic variable access, debugging, and code introspection. This combination allows you to interact with global variables and gain insights into your code during runtime or for other specific purposes. Consider the following illustration to better understand this concept:

Example Code
def calculate_sum_of_globals(): global_sum = sum(value for value in globals().values() if isinstance(value, (int, float))) return global_sum # Global variables num1 = 10 num2 = 20 num3 = 30 # Call the function to calculate the sum of global variables result = calculate_sum_of_globals() # Display the result print("Sum of global variables:", result)

Here, we have defined a function called calculate_sum_of_globals(), and we use it to calculate the sum of numeric global variables in the current module. Inside the function, we use the globals() function to access the global symbol table and retrieve a dictionary containing all the variables and their corresponding values within the global scope. We then use a generator expression (value for value in globals().values() if isinstance(value, (int, float))) to iterate through the values of the global variables.

In the generator expression, we filter the values to include only those that are numeric, specifically integers and floating-point numbers. This is achieved using the isinstance() function with the (int, float) argument. It ensures that we consider only numeric values in the calculation.

We pass the filtered numeric values to the sum() function, which calculates the sum of all these values, representing the sum of numeric global variables. Outside the function, we have three global variables num1, num2, and num3, each assigned with a numeric value.

After calling the function calculate_sum_of_globals(), the result of the sum of the numeric global variables is stored in the result variable. Finally, we print the result, which displays the sum of the numeric global variables as calculated by the function.

Output
Sum of global variables: 60

The above example utilizes globals(), generator expressions, and the sum() function to calculate the sum of numeric global variables in a Python module. Filtering out non-numeric values ensures accurate calculation without errors.

Having gained a thorough understanding of Python’s globals() function, its applications, and its adaptability in diverse situations, you now possess a solid groundwork. To enhance your understanding further, let’s delve into some theoretical concepts that will greatly benefit your journey in Python programming.

Python globals() Limitations

While using the globals() function as a tool to access and introspect global variables, there are some limitations that you should be aware of:

I. Scope Restriction

The globals() function allows you to access only the global symbol table of the current module. Keep in mind that you cannot use globals() to access the global variables of other modules or external code. It is limited to the scope of the current module, making it a valuable tool for managing global variables within that specific context.

II. Read-Only Access

While you can retrieve values of global variables using globals(), modifying the symbol table through this function does not have any effect on the actual global variables. To modify global variables, you need to use assignment statements directly.

III. Limited to Global Variables

As the name suggests, you can use globals() to access only global variables. It’s important to note that you cannot use globals() to access local variables or variables defined within functions or other scopes. This function is specifically designed to work with global variables, allowing you to interact with them efficiently.

Exploring Unique Use Cases of the globals()

Despite its limitations, you have a flexible tool in the globals() function that can prove useful in various scenarios. Let’s explore some unique use cases where globals() can be particularly valuable for you:

I. Dynamic Variable Access

Using globals(), you can access global variables dynamically based on variable names stored in strings or variables.

II. Debugging and Code Introspection

The globals() function is handy for debugging tasks. It allows you to inspect the current state of global variables during runtime.

III. Configuration and Settings Management

In certain scenarios, global variables can be used to store configuration settings. With globals(), you can access and modify these settings dynamically.

IV. Creating Global Variables Programmatically

In some situations, you may need to create global variables dynamically during runtime. The globals() function enables you to achieve this by updating the global symbol table.

Congratulations on learning about the Python globals() function! It’s an exciting achievement that opens up new possibilities in your coding journey. With globals(), you now have the power to access and interact with global variables, functions, and classes like never before. You can read, modify, and even delete global elements directly, making your code more flexible and adaptable.

You learned how to access, modify, and delete elements in lists and tuples using Python globals() function. Moreover, you explored adding checks while using globals(). Lastly, you examined the key differences between globals() and locals(). This knowledge provides you to make the most of global variables and enhance your Python programming skills.

By combining globals() with other Python functions and tools, you can perform dynamic variable access, debugging, and code introspection with ease. It’s like having a superhero sidekick that makes your coding tasks more efficient. But remember, globals() has its limitations too. It can only access the global symbol table of the current module, and it won’t affect local variables or variables defined within functions. So be mindful of its scope.

Now that you’ve equipped yourself with this tool, the possibilities are endless. You can use it for configuration management, dynamic variable access, and more. So go ahead and experiment with Python globals() in your code, and let your coding skills soar to new heights! Happy coding, and keep up the great work!

 
Scroll to Top