🧠 Python Functions and Functional Programming
Estimated reading: 3 minutes 28 views

🧠Python Scope Explained – LEGB Rule, Global, Nonlocal, Best Practices

🧲 Introduction – Why Variable Scope Matters

In Python, scope refers to the area of a program where a variable is recognized and accessible. When your code contains nested functions, global declarations, or built-in names, understanding which variable Python is referring to is crucial.

Python follows a specific LEGB rule to resolve variable names:

  • L – Local
  • E – Enclosing
  • G – Global
  • B – Built-in

Misunderstanding scope often leads to hard-to-find bugs or UnboundLocalError. This guide will help you master scope and avoid such pitfalls.

🎯 In this guide, you’ll learn:

  • The 4 scopes in Python defined by the LEGB rule
  • How Python looks up variables
  • Real-world examples of scope in nested functions
  • When and how to use global and nonlocal

πŸ” The LEGB Rule Explained

πŸ“¦ L – Local Scope

Defined inside a function and accessible only within that function.

def func():
    x = 10  # local scope
    print(x)

🧩 E – Enclosing Scope

Variables from outer functions in nested functions.

def outer():
    y = "enclosing"
    def inner():
        print(y)  # enclosing scope
    inner()

🌍 G – Global Scope

Defined at the top level of a script or module.

x = "global"

def func():
    print(x)  # global variable

βš™οΈ B – Built-in Scope

Names preassigned in Pythonβ€”like len, sum, print, etc.

print(len("Python"))  # Built-in function

πŸ” Scope Lookup Order

When you access a variable, Python searches in this order:

  1. Local (inside current function)
  2. Enclosing (in outer functions)
  3. Global (at module level)
  4. Built-in (Python reserved names)

As soon as Python finds a match, it stops searching.


βœ… Example: LEGB in Action

x = "global"

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

outer()  # Output: local

πŸ“˜ Explanation: The innermost assignment wins due to the LEGB search hierarchy.


πŸ”§ Using global Keyword

Modifies global variables inside functions.

count = 0

def increment():
    global count
    count += 1

⚠️ Use global sparinglyβ€”it makes code harder to debug and test.


πŸ”§ Using nonlocal Keyword

Modifies variables in enclosing (non-global) scope.

def outer():
    x = 10
    def inner():
        nonlocal x
        x += 1
        print(x)
    inner()

outer()  # Output: 11

βœ… Useful for closures and decorators where the inner function needs to update outer variables.


⚠️ Common Pitfalls

IssueExampleFix
UnboundLocalErrorUsing a variable before assigningDeclare variable before use
Overusing globalFrequent global mutationsReturn values instead
Shadowing built-insUsing sum = 10Avoid overwriting built-ins

πŸ’‘ Best Practices

  • βœ… Keep variables local whenever possible
  • βœ… Use nonlocal only when necessary for closures
  • βœ… Avoid using global unless absolutely required
  • βœ… Never shadow built-in names like list, str, sum

πŸ“Œ Summary – Recap & Next Steps

Python uses the LEGB rule (Local, Enclosing, Global, Built-in) to determine variable scope and resolve names during execution. Understanding how this rule works ensures you write clean, predictable, and bug-free code.

πŸ” Key Takeaways:

  • βœ… Variables are resolved in the order: Local β†’ Enclosing β†’ Global β†’ Built-in.
  • βœ… global lets you write to global variables inside functions.
  • βœ… nonlocal allows writing to variables in enclosing (outer) functions.
  • ⚠️ Scope clarity is essential for nested functions and closures.

βš™οΈ Real-World Relevance:
Scope handling is critical in functional programming, decorators, closures, and frameworks like Flask/Django, where multiple nested functions share context.


❓ FAQ Section – Python Scope (LEGB)

❓ What is scope in Python?

βœ… Scope determines where a variable can be accessed. Python uses LEGBβ€”Local, Enclosing, Global, and Built-inβ€”to resolve variable names.

❓ What does LEGB stand for?

βœ… LEGB refers to the order Python searches for variable names:
Local β†’ Enclosing β†’ Global β†’ Built-in.

❓ What is a global variable?

βœ… A global variable is defined at the top level of a Python script and is accessible from any function (unless shadowed).

❓ How do I modify a global variable inside a function?

βœ… Use the global keyword:

global x

❓ What is nonlocal used for?

βœ… The nonlocal keyword allows modification of variables from an enclosing (non-global) scope, typically used in nested functions.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Scope (LEGB)

Or Copy Link

CONTENTS
Scroll to Top