Python globals()

The globals() method returns a dictionary with all the global variables and symbols for the current program.

Example

print(globals())

Output

{'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>}

globals() Syntax

The syntax of the globals() method is:

globals()

globals() Parameters

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


globals() Return Value

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


Example: Python globals()

age = 23

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

Output

The age is: 25

Python compiler maintains a symbol table which contains the necessary information about the program being written. There are two types of symbol tables in Python - Local and Global.

A Global Symbol table stores all the information related to the program's global scope (within the whole program). We can access this symbol table with the globals() method.

Typically, python programmers use the globals() method to modify any global variables in the code.

In this case, we have changed the age variable to 25 using the globals() method with the dictionary key ['age'].


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges