Python globals()
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 =123print(globals())Copy to clipboardCopy 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 clipboardCopy to clipboard
Example 2
length =123globals()['length']=125print('The length is:', length)Copy to clipboardCopy 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: 125Copy to clipboardCopy to clipboard
Codebyte Example
Use globals() to get the symbol table:
Visit usVisit usCodeHide codeOutputHide outputCopy 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
