Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What is variable scope?


Where Python looks for a name, in orderLocal — the current functionEnclosing — any outer functionGlobal — the module or notebookBuilt-in — len, max, print
The first match wins, so max = max(scores) in a notebook hides the built-in max for every later cell.

What you need to know

LEGB in action

Python
x = "global"def outer():    x = "enclosing"    def inner():        return x          # not local -> found in the enclosing scope    return inner()print(outer())            # enclosingprint(x)                  # global -> outer's x never touched this oneprint(len("abc"))         # 3 -> 'len' found in the built-in scope

Assignment makes a name local

Python decides which names are local when it compiles the function, not line by line. If a name is assigned anywhere in the function, it is local everywhere in that function:

Python
count = 0def bump():    count += 1            # reads local 'count' before it has a valuetry:    bump()except UnboundLocalError as e:    print(e)   # cannot access local variable 'count' where it is not associated with a value

Blocks do not create scopes

Python
for i in range(3):    last = iprint(i, last)            # 2 2 -> both still exist after the loopsquares = [n * n for n in range(3)]# print(n)  -> NameError: comprehensions DO have their own scope

Closures

An inner function that uses a variable from an enclosing function "closes over" it and keeps it alive after the outer function returns. This is how decorators and function factories work.

A real-life example

A notebook shadows a built-in, a very common Jupyter bug:

Python
scores = [0.91, 0.87, 0.95]max = max(scores)                 # shadows the built-in max() in the global scopeprint(max)                        # 0.95try:    best_latency = max([120, 95, 210])except TypeError as e:    print(e)                      # 'float' object is not callabledel max                           # removes the global name; built-in is visible againprint(max([120, 95, 210]))        # 210

Because of LEGB, the global max is found before the built-in one. The cell that fails can be fifty cells below the one that caused it. Name variables max_score, total, ids — never max, sum, list, id, input or type.

Follow-up questions to expect

  • "What is UnboundLocalError?" — Reading a local variable before it is assigned. It usually means you assigned to a name you meant to read from an outer scope.
  • "What does nonlocal do?" — It lets an inner function rebind a variable from its enclosing function, the way global does for module variables.
  • "Do comprehensions leak their loop variable?" — Not in Python 3; they have their own scope. Plain for loops do leak.