VOOZH about

URL: https://www.codecademy.com/resources/docs/python/built-in-functions/globals

⇱ Python | Built-in Functions | globals() | Codecademy


Skip to Content

Python globals()

Preview: @mossj22 1 total contribution
@mossj22

1 total contribution

Published Jun 29, 2023

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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 CoursesIncludes 6 Courses
    • With Professional CertificationWith Professional Certification
    • Beginner Friendly.
      75 hours75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With CertificateWith Certificate
    • Beginner Friendly.
      24 hours24 hours

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())
Copy to clipboard
Copy to clipboard

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}
Copy to clipboard
Copy to clipboard

Example 2

length =123
globals()['length']=125
print('The length is:', length)
Copy to clipboard
Copy to clipboard

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
Copy to clipboard
Copy to clipboard

Codebyte Example

Use globals() to get the symbol table:

Visit us
Visit us
Hide code
Code
Output
Hide output
Copy to your clipboard

All contributors

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 CoursesIncludes 6 Courses
    • With Professional CertificationWith Professional Certification
    • Beginner Friendly.
      75 hours75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With CertificateWith Certificate
    • Beginner Friendly.
      24 hours24 hours