liveBook · Manning

Globals

As explained in The Quick Python Book, Fourth Edition

globals is a Python built-in function that returns a dictionary representing the current global namespace bindings.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates returned entries, interactive and function scope, deletion, shadowing, and reimporting, but not dictionary mutation internals.
Examples
Shows interactive namespace listings, imported math and cos bindings, function scope, deletion, and accidental list shadowing.
What it assumes
Assumes general Python use and teaches namespace bindings, built-in lookup, imports, and function locals through examples.
What you can do after
Diagnose scope and name-resolution problems by inspecting global bindings and comparing them with local bindings.
How it connects
Connects globals() with namespaces, scope, locals(), imports, built-ins, name shadowing, del, and importlib.reload.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.