Content · Programming · Python

Python LEGB Scope Resolution Explained

Python resolves ordinary names using local, enclosing, global and built-in scopes, usually called LEGB. Understanding the search order explains why shadowed names have unexpected values.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains legb scope resolution explained through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.

What You Will Learn


Python resolves ordinary names using local, enclosing, global and built-in scopes, usually called LEGB. Understanding the search order explains why shadowed names have unexpected values.

When and Why to Use It


The following example focuses on a practical use of LEGB Scope Resolution Explained.

Step-by-Step Example


name = "global"

def outer():
    name = "enclosing"
    def inner():
        name = "local"
        print(name)
    inner()
    print(name)

outer()
print(name)

Understanding the Example


The inner function prints local, the outer prints enclosing, and module code prints global. Each scope has its own binding named name.

Expected Output


local
enclosing
global

Important Behavior and Edge Cases


A name assigned anywhere in a function is usually local to that function, which can produce UnboundLocalError if read before assignment.

Try It Yourself


Remove the inner local assignment and predict which name it prints.

Common Beginner Mistakes


  • A name assigned anywhere in a function is usually local to that function, which can produce UnboundLocalError if read before assignment.
  • Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
  • Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.

Key Takeaways


  • Python resolves ordinary names using local, enclosing, global and built-in scopes, usually called LEGB.
  • The inner function prints local, the outer prints enclosing, and module code prints global.
  • Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.
Share this resourceSend this page to someone who may find it useful.