Python globals() Function – Access Global Symbol Table

Python globals() Function

The globals() function in Python returns a dictionary representing the current global symbol table. This includes all global variables, functions, and imported modules available at the time of the call.

Syntax

globals()

Parameters:

  • None – globals() does not take any arguments.

Returns:

  • A dictionary representing the current global symbol table.

Example 1: View Global Variables

x = 10
def greet():
    return "Hello"

global_vars = globals()
print(global_vars["x"])
print(global_vars["greet"]())
10
Hello

Example 2: Add a Global Variable Dynamically

globals()["new_var"] = "Python is fun!"
print(new_var)
Python is fun!

Note: We added a global variable new_var without declaring it directly in the code.

Use Case: When Should You Use globals()?

  • To inspect all global variables and their values at runtime.
  • To dynamically access or set global variables by name.
  • In scripting environments or advanced meta-programming scenarios.

Common Mistakes

  • Using globals() inside a function and expecting it to return local variables — it won’t.
  • Modifying the global symbol table inappropriately can lead to code that is hard to understand and debug.

Interview Tip

If you're asked about dynamic variable creation or variable scope, mention globals() as a tool for accessing and manipulating the global namespace.

Summary

  • globals() returns the dictionary of current global variables.
  • You can read and write global values using it.
  • Use with caution — overusing it can reduce code readability.

Practice Problem

Write a program that adds a new global variable using globals() and prints it:

globals()["language"] = "Python"
print(language)