Python scope

  1. A reference to a variable, such as foo (that is not explicitly qualified, such as flimflam.foo), is usually found in the innermost scope, i.e. the innermost textual block of code, where Python blocks are determined by indentation.

    foo = 3
    
    def bar():
        foo = 4
        print(foo)
    
    bar()
    
  2. If no reference is found in the innermost scope then search continues outwards from that scope to the module scope.

    foo = 3
    
    def bar():
        foo = 4
    
        def qux():
            print(foo)
    
        qux()
    
    bar()
    
  3. An exception is if a variable has been declared global in which case the reference is directly to the module scope.

    foo = 3
    
    def bar():
        foo = 4
    
        def qux():
            global foo
            print(foo)
    
        qux()
    
    bar()
    
  4. What happens in each of the following cases?

    foo = 32
    
    def bar():
        global foo
        foo = 88
        return foo
    
    print(bar(), foo)
    
    foo = 32
    
    def bar():
        foo = 88
        return foo
    
    print(bar(), foo)
    
    foo = 32
    
    def bar():
        return foo
    
    print(bar(), foo)
    
  5. There's even an in-between case for a variable that's neither local nor global.

    def outer():
        x = "local"
    
        def inner():
            nonlocal x
            x = "nonlocal"
            print("inner:", x)
    
        inner()
        print("outer:", x)
    
    
    outer()
    

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-09-04 Thu 08:55