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.
answer = 42 print(globals()["answer"]) # 42
Try it
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.
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
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"] = 1creates or changes the variablexfor 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()andlocals()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 theglobalstatement. - Do not overuse it. Writing names dynamically hides them from readers, linters and IDEs. A plain
dictorgetattr(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]raisesKeyErrorfor missing names, unlikegetattr(module, name, default).