Python Scope and the LEGB Rule: Resolving Names in Your Code

Python Scope and the LEGB Rule: Resolving Names in Your Code

by Leodanis Pozo Ramos Publication date Jul 16, 2025 Reading time estimate 49m intermediate python

The scope of a variable in Python determines where in your code that variable is visible and accessible. Python has four general scope levels: local, enclosing, global, and built-in. When searching for a name, Python goes through these scopes in order. It follows the LEGB rule, which stands for Local, Enclosing, Global, and Built-in.

Understanding how Python manages the scope of variables and names is a fundamental skill for you as a Python developer. It helps you avoid unexpected behavior and errors related to name collisions or referencing the wrong variable.

By the end of this tutorial, you’ll understand that:

  • A scope in Python defines where a variable is accessible, following the local, enclosing, global, and built-in (LEGB) rule.
  • A namespace is a dictionary that maps names to objects and determines their scope.
  • The four scope levels—local, enclosing, global, and built-in—each control variable visibility in a specific context.
  • Common scope-related built-in functions include globals() and locals(), which provide access to global and local namespaces.

To get the most out of this tutorial, you should be familiar with Python concepts like