Python Glossary Русский

all Python 3astterm

ast.Global

functions and classes

The node for the statement global a, b: names is a list of plain strings; it declares that assignments in the function go to the global scope.

Syntax

ast.Global(names)

names are strings, not Name nodes, so ast.walk looking for Name will not see global declarations. global affects the whole function, not only from where it is written; using the name before the declaration is a SyntaxError, yet ast.parse lets it through: only compile() reports it, since the symbol table is built later. nonlocal is a separate Nonlocal node.

Examples

import ast
fn = ast.parse('def f():\n    global counter, total\n    counter += 1').body[0]
g = fn.body[0]
print(type(g).__name__, g.names)  # → Global ['counter', 'total']
import ast
src = 'def f():\n    x = 1\n    global x'
tree = ast.parse(src)
print(type(tree.body[0].body[1]).__name__)  # → Global
try:
    compile(tree, '<f>', 'exec')
except SyntaxError as e:
    print(type(e).__name__)  # → SyntaxError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy