Python Glossary Русский

all Python 3Built-in functionsterm

globals

namespaces

Returns the dictionary of the global namespace of the current module.

Syntax

globals()

What you get is the module's live namespace dictionary, not a snapshot, so assigning into it really does create a global — unlike writing into locals() inside a function, which generally has no effect. That tempts people into manufacturing variable names at runtime; a plain dictionary is nearly always the better answer, since generated names are invisible to readers and linters alike. Called inside a function, globals() still points at the module where that function was defined, not at the caller's module.

Examples

x = 42
print('x' in globals())  # → True
print(globals()['x'])  # → 42
globals()['new_var'] = 99
print(new_var)  # → 99
print(type(globals()))  # → dict
print('print' in dir(__builtins__))  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy