globals()

mossj22's avatar
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 = 123
print(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 = 123
globals()['length'] = 125
print('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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy