Python 101Free
FUNCTIONS

Scope and Closures

Where names live and how nested functions remember them.

SECTION 01

The LEGB rule

When Python sees a name in a function, it looks for the binding in four scopes, in order. Local first (the function itself), then Enclosing (any outer function that wraps this one), then Global (the module's top level), then Builtin (len, range, print, and friends).

This is the LEGB rule, and it determines what every name resolves to. The first scope that has a binding wins, the rest are not consulted.

Most confusion about scope comes from accidentally shadowing a builtin (def list(...) is a bad idea) or trying to assign to a global from inside a function (which creates a local instead, unless you use global). The rule is mechanical, but the consequences take a minute to digest.

1 more section

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in