Python Glossary Русский

all Python 3Functionsterm

Local and global variables

scope

The LEGB rule: Local → Enclosing → Global → Built-in. A local variable exists only inside its function.

Syntax

x = 10  # глобальная
def f():
    x = 5  # локальная

The main trap: assigning to a name anywhere in a function makes it local for the whole body — so you cannot read the global x and then write x = ... below it; that raises UnboundLocalError on the read. Reading globals needs no declaration, but to assign to a global instead of creating a new local you need global; for a variable from an enclosing function, nonlocal.

Examples

x = 'global'
def f():
    x = 'local'
    print(x)  # → local
f()
print(x)  # → global
count = 0
def inc():
    global count
    count += 1
inc()
print(count)  # → 1
def outer():
    n = 10
    def inner():
        nonlocal n
        n += 1
    inner()
    return n
print(outer())  # → 11
# Ловушка: чтение до присваивания
x2 = 5
def bad():
    print(x2)  # UnboundLocalError!
    x2 = 10
# Встроенные имена
def f2():
    print(len([1,2,3]))  # → 3 (built-in)
f2()
# Enclosing
def outer2():
    msg = 'hi'
    def inner2():
        print(msg)  # → hi (enclosing)
    inner2()
outer2()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy