globals() returns a dictionary containing the bindings in the current global namespace. Inspecting it reveals names for variables, imported modules, functions, and interpreter-managed entries. section 10.7
Inspecting global bindings
z = 2 import math from cmath import cos globals() # Includes entries resembling: # 'z': 2 # 'math': <module 'math' ...> # 'cos': <function cmath.cos(...)> math.ceil(3.4) # 4
Global and local namespaces can coincide in an interactive session, but a function has its own local bindings. A function can inspect the surrounding module's globals while locals() shows parameters and variables created during the call. section 10.7
Use globals() chiefly to:
- Inspect names currently available in a module or interactive session. section 10.7.1
- Debug accidental name replacement: a later binding can hide a built-in or replace an earlier value. section 10.7.1
Removing a binding
del z, math, cos math.ceil(3.4) # NameError import math math.ceil(3.4) # 4
The returned dictionary reflects bindings such as __name__, __doc__, and __builtins__, alongside names created by the program. Use del to remove an unwanted binding; reimporting restores the name, but does not reload changed module code. section 10.7
