Tutorials Logic, IN info@tutorialslogic.com

Scopes in Python LEGB Rule

Scopes in Python LEGB Rule

Scopes in Python LEGB Rule is an important Python topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Scopes in Python LEGB Rule solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of Scopes in Python LEGB Rule should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Scopes in Python LEGB Rule should be studied as a practical Python lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the python > scopes page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

What is Scope?

Scope determines where a variable is accessible. Python uses the LEGB rule to resolve variable names - it searches in this order:

  • Local - inside the current function
  • Enclosing - in any enclosing functions (closures)
  • Global - at the module (file) level
  • Built-in - Python's built-in names (print, len, etc.)

Local Scope

Local Scope

Local Scope
def my_function():
    x = 10   # local variable - only exists inside this function
    print(x)

my_function()   # 10
# print(x)      # NameError: name 'x' is not defined

# Each function call gets its own local scope
def counter():
    count = 0
    count += 1
    return count

print(counter())  # 1
print(counter())  # 1 (fresh scope each call)

Global Scope

Global Scope

Global Scope
message = "Hello"   # global variable

def greet():
    print(message)  # can READ global variable

greet()   # Hello

# To MODIFY a global variable inside a function, use 'global'
count = 0

def increment():
    global count
    count += 1

increment()
increment()
print(count)   # 2

# Without 'global', Python creates a new local variable
def bad_increment():
    count = count + 1  # UnboundLocalError!

Enclosing Scope & Closures

When a nested function references a variable from its enclosing function, it creates a closure.

Closures

Closures
def outer(x):
    def inner(y):
        return x + y   # 'x' is from enclosing scope
    return inner

add5 = outer(5)
add10 = outer(10)

print(add5(3))    # 8
print(add10(3))   # 13

# Closure remembers the enclosing scope
def make_counter():
    count = 0
    def increment():
        nonlocal count   # modify enclosing variable
        count += 1
        return count
    return increment

counter = make_counter()
print(counter())  # 1
print(counter())  # 2
print(counter())  # 3

# Each call to make_counter() creates an independent counter
counter2 = make_counter()
print(counter2()) # 1 (independent)

nonlocal Keyword

nonlocal

nonlocal
def outer():
    x = 10

    def inner():
        nonlocal x   # refers to outer's x
        x = 20
        print(f"inner: x = {x}")

    inner()
    print(f"outer: x = {x}")   # x was modified by inner

outer()
# inner: x = 20
# outer: x = 20

# LEGB in action
x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)   # local

    inner()
    print(x)       # enclosing

outer()
print(x)           # global

Built-in Scope

Built-in Names

Built-in Names
import builtins

# See all built-in names
print(dir(builtins))

# Built-ins are always available
print(len([1, 2, 3]))   # 3
print(type("hello"))    # <class 'str'>
print(range(5))         # range(0, 5)

# You can shadow built-ins (but don't!)
# list = [1, 2, 3]   # now 'list' is a variable, not the built-in!
# list([1, 2])        # TypeError!

# Check if a name is a built-in
print(hasattr(builtins, "print"))   # True
print(hasattr(builtins, "myvar"))   # False

Detailed Learning Notes for Scopes in Python LEGB Rule

When studying Scopes in Python LEGB Rule, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In Python, Scopes in Python LEGB Rule becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Scopes in Python LEGB Rule focused Python check

Scopes in Python LEGB Rule focused Python check
def review_scopes-in-python-legb-rule():
    value = "sample"
    if value:
        print("Scopes in Python LEGB Rule: normal path is ready")
    else:
        print("Scopes in Python LEGB Rule: handle the empty path first")

review_scopes-in-python-legb-rule()

Scopes in Python LEGB Rule validation path

Scopes in Python LEGB Rule validation path
items = []
if not items:
    print("Scopes in Python LEGB Rule: no data available, show a fallback")
else:
    print(items[0])
Key Takeaways
  • Explain the purpose of Scopes in Python LEGB Rule before memorizing syntax.
  • Run or trace one small Python example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Scopes in Python LEGB Rule.
  • Write the rule in your own words after checking the example.
  • Connect Scopes in Python LEGB Rule to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Scopes in Python LEGB Rule without the situation where it is useful.
RIGHT Connect Scopes in Python LEGB Rule to a concrete Python task.
Purpose makes syntax easier to recall.
WRONG Testing Scopes in Python LEGB Rule only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Scopes in Python LEGB Rule.
Evidence keeps debugging focused.
WRONG Memorizing Scopes in Python LEGB Rule without the situation where it is useful.
RIGHT Connect Scopes in Python LEGB Rule to a concrete Python task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Scopes in Python LEGB Rule, then fix it and explain the fix.
  • Summarize when to use Scopes in Python LEGB Rule and when another approach is better.
  • Write a small example that uses Scopes in Python LEGB Rule in a realistic Python scenario.
  • Change one important value in the Scopes in Python LEGB Rule example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Python, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.