Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python globals() function

Reference for Python globals(): get the current module's global namespace as a dictionary, read and create variables by name, and how it differs from locals().

globals() returns the dictionary that holds the global variables of the current module: every top-level name, such as functions, classes, imported modules and ordinary variables. It is the real namespace, not a copy, so changing the dictionary changes the variables.

It is handy for introspection and for rare dynamic tricks, such as looking up a function by name or defining names in a loop. For most tasks a dictionary of your own is clearer and safer than writing into the global namespace.

Python
answer = 42
print(globals()["answer"])
# 42

Try it

Python Reading and writing globals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Globals versus locals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
globals()

The function takes no arguments.

Return value: the dictionary of the current module's namespace. The same dictionary is returned on every call from the same module.

Usage notes

  • It is live. Assigning globals()["x"] = 1 creates or changes the variable x for the whole module. Deleting a key removes the name.
  • Module scope, not caller scope. It returns the globals of the module where the code was defined, even when called from a function in another module that imported it.
  • Contains housekeeping entries such as __name__, __doc__, __builtins__ and __file__ (where available). Filter names starting with __ when you list your own.
  • At the top level of a script or module, globals() and locals() return the same dictionary.
  • Inside a function locals() is a different thing, containing only the function's local variables. To change a global from a function with normal syntax, use the global statement.
  • Do not overuse it. Writing names dynamically hides them from readers, linters and IDEs. A plain dict or getattr(module, name) is usually better.
  • Interactive and notebook environments store your variables here too, which is why it shows what you defined so far.
  • Functions in dispatch tables: globals()[name] raises KeyError for missing names, unlike getattr(module, name, default).