Python - Scope

python logo pixel art

Python scope determines how and where a variable can be accessed.


Global vs Local

The main difference is that global variables can be accessed from anywhere in the code, while local variables are only accessible within their specific scope.


Only classes, functions and modules provide scope in Python.

Global Scope

A variable created in the top-level scope or with the `global` keyword will be global.

x = 32

def doSomething():
  print(x) # 32
def doSomething():
  global x
  x = 32 
  print(x) # 32

doSomething()
print(x) # 32

Local Scope

A variable created within a scope will be local to that scope.

def doSomething():
  x = 4
  print(x)
def doSomething():
  x = 4
  y = 6
  def  _print():
    print(x, y) # 4, 6
  _print()

nonlocal

nonlocal is used in nested functions to access variables from an outer (but non-global) scope.

# without nonlocal
def doSomething():
    x = 4
    def inner():
        x = 6
        print(x) # 6
    inner()
    print(x) # 4

doSomething()
# with nonlocal
def doSomething():
    x = 4
    def inner():
        nonlocal x
        x = 6
        print(x) # 6
    inner()
    print(x) # 6

doSomething()