[Python] UnboundLocalError (Variable Scope inside a Function)

lst = [1, 2, 3]

def foo():
  lst.append(5)  # OK
  lst += [5]     # ERROR here

foo()

lst += [5]lst = lst + [5]

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global (global lst) for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Ref: Python Programming FAQ

#UnboundLocalError

Last Updated on 2023/08/24 by A1go

Bitnami