Python globals() Function

Returns the global symbol table as a dictionary

Example: Print the current global symbol table

a = 10
b = 20
c = 30
d = 40

x = globals()
print(x)

Output:

{'__name__': '__main__',
 '__doc__': None,
 '__package__': None,
 '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fed1a254358>,
 '__spec__': None,
 '__annotations__': {},
 '__builtins__': <module 'builtins' (built-in)>,
 '__file__': 'main.py',
 '__cached__': None,
 'a': 10,
 'b': 20,
 'c': 30,
 'd': 40, 'x': {...}}

Highlighted pairs are global variables, declared earlier.

Usage

The globals() function returns the global symbol table as a dictionary.

It contains information about all global variables.

Each key in the dictionary holds the name of the variable.

This dictionary is also accessible from within functions and can be used to update global variables directly.

Syntax

globals()

What is a symbol table?

A symbol table is maintained by a compiler.

It contains necessary information about the current program.

There are two kinds of symbol table.

  • Local symbol table – contains information related to the local scope of the program
  • Global symbol table – contains information related to the global scope of the program

Why is it necessary?

Python gives the programmer a large number of tools for introspecting the running environment.

globals() is just one of those, and it can be very useful in a debugging session to see what objects the global scope actually contains.

Global and Local Scope

A variable declared outside a function has a Global Scope and can be accessed inside or outside of a function. But you cannot update it inside a function.

However, a variable declared within a function has a Local Scope and can only be accessed within that function.

Example:

x = 5   # global scope

def myfunc():
    x = 10   # local scope
	
	# print local x
    print('x inside function is', x)

myfunc()

# print global x
print('x outside function is', x)

Output:

x inside function is 10
x outside function is 5

Access global variables

As globals() method returns a dictionary, you can perform any operation that a dictionary supports, like indexing, iteration etc.

Example: Get the value of global variable ‘x’

x = 10
print(globals()['x'])   # 10

Example: Get the filename of the current program

print(globals()['__file__'])	# main.py

Modify global variables

Using globals() function you can update a global variable from a no-global scope, e.g. inside a function.

Example: Update global variable x inside a function

x = 5	# global scope
  
def myfunc():
	x = 10	# local scope

	# update global x
	globals()['x'] = 99
	
	# print local x
	print('x inside function is', x)

myfunc()

# print global x
print('x outside function is', x)

Output:

x inside function is 10
x outside function is 99