Python globals()

The globals() method returns the dictionary of the current global symbol table.

A symbol table is a data structure maintained by a compiler which contains all necessary information about the program.

These include variable names, methods, classes, etc.

There are mainly two kinds of symbol table.

  1. Local symbol table
  2. Global symbol table

Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method.

The local scope could be within a function, within a class, etc.

Likewise, a Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method.

The global scope contains all functions, variables which are not associated to any class or function.

Recommended Reading: Namespace and scope of in Python


Syntax of globals()

The globals table dictionary is the dictionary of the current module (inside a function, this is a module where it is defined, not the module where it is called).

The syntax of globals() method is:

globals()

globals() Parameters

The globals() method doesn't take any parameters.


Return value from globals()

The globals() method returns the dictionary of the current global symbol table.


Example 1: How globals() method works in Python?

globals()

When you run the program, the output will be:

{'In': ['', 'globals()'],
 'Out': {},
 '_': '',
 '__': '',
 '___': '',
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '__name__': '__main__',
 '_dh': ['/home/repl'],
 '_i': '',
 '_i1': 'globals()',
 '_ih': ['', 'globals()'],
 '_ii': '',
 '_iii': '',
 '_oh': {},
 '_sh': <module 'IPython.core.shadowns' from '/usr/local/lib/python3.5/dist-packages/IPython/core/shadowns.py'>,
 'exit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>,
 'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.core.interactiveshell.InteractiveShell object at 0x7fbc6478ee48>>,
 'quit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>}

The output shows the all global variables and other symbols for the current program.


Example 2: Modify global variable using global()

age = 23

globals()['age'] = 25
print('The age is:', age)

When you run the program, the output will be:

The age is: 25

Here, since the global symbol table also stores all global variables, i.e. in this case, age, the value of age can be changed using the globals() function.

The dictionary returned is accessed using key of the variable age and modified to 25.

This is reflected to the global symbol table again.