Glossary

Scope

Scope determines where a variable name is visible and accessible in a Python program. Python uses the LEGB rule to resolve names, searching four scopes in order: Local (inside the current function), Enclosing (inside any enclosing functions, for nested functions), Global (at the module level), and Built-in (the builtins module containing print, len, range, etc.).

A variable created inside a function is local by default and ceases to exist when the function returns. To assign to a global variable from inside a function, you must declare it with the global keyword; to assign to a variable in an enclosing function's scope, you use nonlocal. Without these declarations, assignment always creates a new local variable, even if a variable with the same name exists in an outer scope.

Understanding scope is essential for avoiding subtle bugs. A common mistake is reading a global variable inside a function (which works fine) and then later adding an assignment to it (which makes it local throughout the entire function, causing an UnboundLocalError if the read precedes the assignment). The LEGB rule also explains why you can shadow built-in names — defining a variable called list hides the built-in list type — and why doing so is a bad idea.

Related terms: LEGB Rule, Closure, Function, Variable

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.