globals()
Published Jun 29, 2023
Contribute to Docs
The built-in globals()
function allows access to the global scope’s name table, which is a writable dictionary containing the current global names and their corresponding values in the code. This function can be used to access or modify the value of a global variable from within functions.
Syntax
globals()
- This method doesn’t take any parameters.
- This method returns the dictionary of the current global symbol table.
Example 1
length = 123print(globals())
This code returns the following dictionary. Notice that the length
global variable is listed in the dictionary.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'length': 123}
Example 2
length = 123globals()['length'] = 125print('The length is:', length)
The global variable in this example is modified using the globals()
function with the dictionary key [length]
. It can be also modified from within a function.
The code will return:
The length is: 125
Codebyte Example
Use globals()
to get the symbol table:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours