Python Variable Scope Guide: LEGB, global & nonlocal

目次

1. Introduction: What is Python’s variable scope?

When learning Python, you may encounter the concept of a “variable scope (Scope)”. Scope refers to the range where a variable can be accessed, and misunderstanding it can lead to unexpected errors and bugs. For example, let’s look at the following code.
def my_function():
    x = 10  # This variable x is only valid within the function

print(x)  # NameError: name 'x' is not defined
In this code, an error occurs because it tries to reference the variable x defined inside the function my_function from outside the function. This is because x belongs to the “local scope”, so it is considered nonexistent outside the function. In this article, we will thoroughly explain everything from the basics of Python’s variable scope to advanced usage and error avoidance techniques. Let’s understand scopes correctly and learn how to manage them properly.

2. Basics of Variable Scope

2.1 What Is Variable Scope?

Variable scope is the concept that refers to the region where a variable is valid. In Python, the range where a variable can be referenced is determined by where the variable was defined. For example, a variable defined inside a function cannot be accessed from outside that function. Conversely, a variable defined at the module level is available throughout the entire script.

2.2 Why Do You Need to Understand Scope?

If you don’t manage variable scope properly, the following problems can arise.
  • Unintended variable overwriting Using the same variable name in different scopes can lead to unexpected bugs.
  • Variable not found (NameError) Attempting to access a variable without understanding its scope can raise a NameError.
  • Reduced code readability Overusing global-scope variables makes the code’s intent unclear and debugging difficult.

2.3 Basic Rules of Python Scope

To understand Python’s scope rules, keep the following points in mind.
  1. Variables defined inside a function are only valid within that function (local scope)
  2. Variables defined outside functions are accessible throughout the script (global scope)
  3. Python has a “LEGB rule” that defines the order of scope lookup
  4. To modify a global variable inside a function, use the global keyword
  5. To modify an outer variable in a nested function, use the nonlocal keyword
In this way, properly managing scope in Python helps prevent unexpected bugs and enables efficient coding.
年収訴求

3. Types of Python Scopes and Examples

Python variable scopes can be broadly divided into four types. Understanding each scope and managing variables appropriately is a key point for writing bug‑free code.
  • Local Scope
  • Enclosing Scope
  • Global Scope
  • Built-in Scope
In this section, we will explain each scope in detail with concrete examples.

3.1 Local Scope (Local Scope)

A local scope is the scope of variables defined inside a function. Variables in a local scope are only valid within that function and cannot be accessed from outside the function.

Example of Local Scope

def my_function():
    x = 10  # x is a local variable of this function
    print(x)  # This works fine

my_function()
print(x)  # NameError: name 'x' is not defined
Explanation: The x defined inside the function my_function is only valid while the function is executing. Attempting to access x from outside the function raises a NameError.

3.2 Enclosing Scope (Enclosing Scope)

An enclosing scope refers to the function scope of an outer function for a nested (inner) function. The inner function (child) can access variables of the outer function (parent).

Example of Enclosing Scope

def outer_function():
    y = 20  # variable in the parent function's scope

    def inner_function():
        print(y)  # can reference the parent function's variable inside the child function

    inner_function()

outer_function()
Explanation: Inside inner_function, you can reference the variable y from outer_function.

3.3 Global Scope (Global Scope)

A global scope is the scope of variables that are valid throughout the entire script (module). Variables defined outside functions can be referenced from anywhere in the script.

Example of Global Scope

z = 30  # global variable

def my_function():
    print(z)  # can access global variable

my_function()
print(z)  # can be referenced anywhere

3.4 Built-in Scope (Built-in Scope)

The built-in scope is the scope of built-in functions and variables that Python provides from the start. Functions such as print() and len() fall under this.

Example of Built-in Scope

print(len([1, 2, 3]))  # Output: 3
Explanation: print and len are Python’s built-in functions and can be used from any scope.

3.5 Summary of the Four Scopes

Scope NameDescriptionExample
Local ScopeVariables valid only inside a functionVariable inside a function
Enclosing ScopeCan reference variables of the outer functionVariables of a nested function
Global ScopeVariables that can be referenced throughout the scriptglobal variable
Built-in ScopePython built-in functions and variablesprint(), len()

4. Variable Scope Lookup Order (LEGB Rule)

In Python, when referencing a variable, it searches for the variable according to a specific rule. This rule is called the LEGB (Local, Enclosing, Global, Built-in) rule, and it searches for variables in the following order.
  1. L (Local) Local Scope – Variables defined within the current function
  2. E (Enclosing) Enclosing Scope – Variables of an outer function (nested function)
  3. G (Global) Global Scope – Variables defined at the module level
  4. B (Built-in) Built-in Scope – Built-in functions and variables provided by Python from the start
Understanding this rule allows you to predict how Python resolves variables, making it easier to avoid errors.

4.1 Concrete Example of the LEGB Rule

x = "global variable"  # G (Global)

def outer_function():
    x = "enclosing variable"  # E (Enclosing)

    def inner_function():
        x = "local variable"  # L (Local)
        print(x)  # According to the LEGB rule, refers to the innermost x

    inner_function()

outer_function()
print(x)  # Refers to the x in the global scope

Output

local variable
global variable

4.2 Effects of Global Scope

If you try to modify a global variable within a local scope, an UnboundLocalError may occur due to the LEGB rule.

Attempting to modify a global variable locally causes an error

x = 10  # global variable

def update_x():
    x += 1  # error occurs
    print(x)

update_x()

Error Message

UnboundLocalError: local variable 'x' referenced before assignment

Solution: Use the global keyword

x = 10  # global variable

def update_x():
    global x  # explicitly specify the global variable
    x += 1
    print(x)

update_x()  # output: 11

4.3 Changing Scope Using nonlocal

If you want to modify a variable in the E (Enclosing) Enclosing Scope of the LEGB rule, use the nonlocal keyword.

Concrete Example of nonlocal

def outer_function():
    count = 0  # variable of the outer function

    def inner_function():
        nonlocal count  # refer to the variable of the outer function
        count += 1
        print(count)

    inner_function()
    print(f"Final count: {count}")

outer_function()

Output

1
Final count: 1

4.4 Searching Built-in Functions (Built-in Scope)

Python has built-in functions such as print() and len(), which belong to the outermost scope (Built-in).

Example of Overriding a Built-in Function

sum = 100  # `sum()` is a built-in function, but it was overwritten as a variable

print(sum([1, 2, 3]))  # TypeError: 'int' object is not callable

Solution: Do Not Overwrite Built-in Functions

del sum  # remove the overwrite
print(sum([1, 2, 3]))  # works correctly

4.5 Summary of the LEGB Rule

ScopeDescriptionExample
L (Local)Variables defined within a functiondef func(): x = 1
E (Enclosing)Variables defined in an outer functionNested function
G (Global)Variables defined at the module levelx = 10 (outside any function)
B (Built-in)Python’s built-in functionsprint(), len()
Understanding the LEGB rule helps you gain a deeper understanding of Python’s variable scope mechanism and prevents errors.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

5. Distinguishing Between Global and Local Variables

In Python, it is important to properly manage whether variables are placed in the global scope or limited to the local scope</>. Overusing global variables reduces code readability and makes bugs more likely. In this section, we will explain in detail understanding the differences between global and local variables and how to use them appropriately.

5.1 What Is a Global Variable?

Global Variable refers to a variable defined outside of functions that can be accessed throughout the entire script.

Example of a Global Variable

count = 0  # Global variable

def increment():
    global count  # Use global variable
    count += 1

increment()
print(count)  # Output: 1

5.2 What Is a Local Variable?

Local Variable refers to a variable defined inside a function that is only valid within that function.

of a Local Variable

def my_function():
    x = 10  # Local variable
    print(x)

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

5.3 global Cases Where You Should Use the Keyword

Typically, the use of global variables should be minimized, but in certain cases using the global keyword is appropriate.

Appropriate Cases

  • When managing configuration values or constants
  • When multiple functions need to share the same variable

Example: Managing Configuration Values

MAX_USERS = 100  # Global variable (treated as a constant)

def print_max_users():
    print(f"Maximum users: {MAX_USERS}")

print_max_users()  # Output: Maximum users: 100

5.4 Managing Variables Without Using global

Instead of using global variables, you can manage data more safely by leveraging function arguments and return values.

Using Function Arguments and Return Values

def increment(value):
    return value + 1

counter = 0
counter = increment(counter)  # Assign the function's return value
print(counter)  # Output: 1

5.5 Summary of Using Global and Local Variables

ItemGlobal VariableLocal Variable
Definition LocationOutside functionsInside functions
Access ScopeAccessible throughout the scriptOnly within the defining function
Impact of ChangesMay affect all functionsImpact is limited
AdvantagesAccessible from anywhereHigher function independence
DisadvantagesChanges are hard to trackHard to use outside functions
Recommended UsageManaging constants and configuration valuesUse local variables whenever possible
Minimizing the use of global variables and leveraging local variables is the best practice.When passing data between functions, it is advisable to use function arguments and return values.

6. Nested Functions and nonlocal Keyword

In Python, you can define a function inside another function. This is called a nested (inner) function. Using nested functions appropriately helps organize code structure and manage scope more finely. Also, if you want to modify a variable from the outer function within a nested function, you need to use the nonlocal keyword. This section provides a detailed explanation of the role and usage of nonlocal.

6.1 What is a Nested Function?

Nested Function refers to defining a function inside another function.

Example of a Nested Function

def outer_function():
    def inner_function():
        print("This is the inner function")

    inner_function()  # Call the inner function from the outer function

outer_function()  # Output: This is the inner function

6.2 Modifying an Outer Function’s Variable Using nonlocal

Normally, trying to modify a variable from the outer function inside an inner function results in an error.

Example that Raises an Error

def outer_function():
    count = 0  # Variable in the outer function

    def inner_function():
        count += 1  # Error occurs
        print(count)

    inner_function()

outer_function()

Solution: Use the nonlocal Keyword

def outer_function():
    count = 0  # Variable in the outer function

    def inner_function():
        nonlocal count  # Referencing the outer function's variable
        count += 1
        print(count)

    inner_function()
    print(count)  # The count modified inside `inner_function` is reflected

outer_function()

Output

1
1

6.3 Differences Between global and nonlocal

KeywordScope AffectedSpecific Use
globalGlobal variables across the entire moduleModify a global variable from within a function
nonlocalVariable of the outer function (enclosing scope)Modify the outer function’s variable within a nested function

Example Using global

count = 0  # Global variable

def increment():
    global count  # Modify the global variable
    count += 1

increment()
print(count)  # Output: 1

Example Using nonlocal

def outer():
    count = 0  # Variable in the enclosing scope

    def inner():
        nonlocal count  # Modify the outer function's variable
        count += 1

    inner()
    print(count)  # Output: 1

outer()
global is used to modify a global variable from within a function.nonlocal is used to modify an outer variable within a nested function.

7. Common Scope-Related Errors and Their Solutions

If you don’t have a proper understanding of Python’s scope, issues such as “variable not found”, “unexpected value changes”, “errors caused by misuse of scope” can arise. In this section, we explain the causes of common scope-related errors and how to resolve them.

7.1 UnboundLocalError: Assigning Before Variable Reference

Error Example

count = 0  # global variable

def increment():
    count += 1  # error occurs here
    print(count)

increment()

Error Details

UnboundLocalError: local variable 'count' referenced before assignment

Solution ①: Use the global Keyword

count = 0  # global variable

def increment():
    global count  # explicitly declare global variable
    count += 1
    print(count)

increment()  # output: 1

Solution ②: Use Function Arguments

def increment(count):
    return count + 1

count = 0
count = increment(count)
print(count)  # output: 1

7.2 NameError: Variable Not Defined

Error Example

def print_message():
    print(message)  # error occurs here

print_message()

Error Details

NameError: name 'message' is not defined

Solution

Define the variable inside the function or pass it as an argument.
def print_message(message):
    print(message)

print_message("Hello")  # output: Hello

7.3 TypeError: Variable Named Same as Built-in Function

If you define a variable with the same name as a Python built-in function, a TypeError can occur when you call the function.

Error Example

sum = 100  # variable with the same name as built-in function `sum()`

print(sum([1, 2, 3]))  # error occurs here

Error Details

TypeError: 'int' object is not callable

Solution

  1. Rename the Variable
total = 100  # use `total` instead of `sum`
print(sum([1, 2, 3]))  # works correctly
  1. If you have overwritten a built-in function, delete it
sum = 100
del sum  # undo the overwrite

print(sum([1, 2, 3]))  # works correctly

7.4 Best Practices for Preventing Scope-Related Errors

Use local variables whenever possible (limiting scope helps prevent unexpected changes) ✅ Do not modify global variables inside functions (avoid using global as much as possible; manage via arguments and return values) ✅ Check that you are not using variable names that clash with built-in functionsBe aware of variable scope and choose the appropriate scope

8. Tips for Proper Scope Management

Python’s scope should be managed properly because it is crucial for improving code readability and preventing bugs. In particular, the misuse of global variables and improper scope management can cause unintended behavior and make debugging difficult. This section introduces practical tips for managing scope effectively.

8.1 Minimize Global Variables

Global variables can be accessed from anywhere, making unintended value changes more likely. Therefore, it is recommended to keep the use of global variables to a minimum.

Bad Example (Abuse of Global Variables)

counter = 0  # Global variable

def increment():
    global counter  # Modify global variable
    counter += 1

increment()
print(counter)  # Output: 1

Good Example (Using Function Arguments and Return Values)

def increment(value):
    return value + 1

counter = 0
counter = increment(counter)
print(counter)  # Output: 1

8.2 Clarify Function Scope

Properly managing a function’s scope allows you to limit the variable’s impact area and prevent unintended changes.

Good Example (Leveraging Local Scope)

def calculate_square(number):
    result = number ** 2  # Local variable
    return result

print(calculate_square(4))  # Output: 16

8.3 global and nonlocal Proper Use

Use Cases for global

  • When managing configuration values or constants
  • Variables that hold state (e.g., singleton pattern)
MAX_USERS = 100  # Global variable (treated as constant)

def get_max_users():
    return MAX_USERS

print(get_max_users())  # Output: 100

Use Cases for nonlocal

  • When modifying an outer variable inside a nested function
def outer():
    count = 0  # Variable of the outer function

    def inner():
        nonlocal count  # Modify outer variable
        count += 1
        print(count)

    inner()

outer()  # Output: 1

8.4 Checklist for Scope Management

Are variables that are confined within a function using local variables instead of globals?If using global variables, is it truly necessary? (e.g., configuration values or constants)When passing data between functions, are you using arguments and return values instead of globals?Is the use of global or nonlocal appropriate? (Not used unnecessarily)Are you avoiding variables that share names with built-in functions?Are you designing code with variable scope in mind? By using this checklist, you can prevent scope-related issues in advance and write code that is safer and easier to maintain.

9. FAQ (Frequently Asked Questions and Answers)

In this section, we have compiled frequently asked questions about Python variable scope. We explain them in a Q&A format to clear up scope misconceptions and deepen practical understanding.

9.1 How can you manage global variables without using global?

A: By using function arguments and return values, you can avoid modifying global variables.

def increment(value):
    return value + 1

count = 10
count = increment(count)
print(count)  # Output: 11
Using this approach makes functions independent and improves reusability.

9.2 What is the difference between nonlocal and global?

A: nonlocal is used to modify variables in the enclosingh4>

KeywordScope AffectedTypical Use
globalGlobal variableModify module-level variables
nonlocalVariable of the outer function (enclosing scope)Modify variables of a nested function

Example of nonlocal

def outer():
    count = 0  # Variable of the outer function

    def inner():
        nonlocal count  # Modify the outer variable
        count += 1

    inner()
    print(count)  # Output: 1

outer()

9.3 What is the LEGB rule?

A: It is a rule that defines the order in which variables are looked up.

  1. L (Local): Variables defined inside a function
  2. E (Enclosing): Variables from the outer function of a nested function
  3. G (Global): Variables in the global scope
  4. B (Built-in): Python’s built-in functions

Example of the LEGB rule

x = "global variable"  # G

def outer():
    x = "enclosing variable"  # E

    def inner():
        x = "local variable"  # L
        print(x)  # According to the LEGB rule, refers to the innermost x

    inner()

outer()
print(x)  # Refers to the global variable
Understanding the LEGB rule helps you grasp how Python variable scope works.

10. Summary

In this article, we explained Python’s variable scope in detail. By understanding and managing scopes properly, you can prevent bugs and write highly readable code.

10.1 Basics of Python Scope

What is a scope?
  • The rule that determines the region where a variable can be accessed.
  • Local scope (inside functions) and global scope (outside functions) are the basics.
Why do you need to understand scopes?
  • Prevent unintended overwriting of variables.
  • Avoid errors where a variable is not found (such as NameError).
  • Improve code readability and make debugging easier.

10.2 Types of Python Scopes

Python has four types of scopes, and variables are looked up according to the LEGB rule.
ScopeDescriptionExample
L (Local)Variable defined inside a function
E (Enclosing)Variable defined in an outer functionNested function
G (Global)Variable accessible throughout the scriptx = 10 (outside any function)
B (Built-in)Python’s built‑in functions and variablesprint(), len()

10.3 Proper Use of global and nonlocal

When to use global
  • When managing constants or configuration values
  • When multiple functions need to share a common variable
When to use nonlocal
  • When you need to modify a variable from an outer function inside a nested function

10.4 Best Practices for Scope Management

Minimize the use of global variables and favor local variables.When sharing data between functions, use arguments and return values—this is the best practice.Understand the scope rules (LEGB) and be aware of the variable lookup order.

10.5 Final Thoughts

A correct understanding and management of scopes is essential for improving your Python programming skills. In particular, being mindful to “avoid abusing global variables” and “clearly define function scopes” leads to better code. Master Python scopes and aim to write safer, more maintainable code! 🚀

10. Summary

In this article, we explained Python’s variable scope in detail. By understanding and managing scopes properly, you can prevent bugs and write highly readable code.

10.1 Basics of Python Scope

What is a scope?
  • The rule that determines the region where a variable can be accessed.
  • Local scope (inside functions) and global scope (outside functions) are the basics.
Why do you need to understand scopes?
  • Prevent unintended overwriting of variables.
  • Avoid errors where a variable is not found (such as NameError).
  • Improve code readability and make debugging easier.

10.2 Types of Python Scopes

Python has four types of scopes, and variables are looked up according to the LEGB rule.
ScopeDescriptionExample
L (Local)Variable defined inside a function
E (Enclosing)Variable defined in an outer functionNested function
G (Global)Variable accessible throughout the scriptx = 10 (outside any function)
B (Built-in)Python’s built‑in functions and variablesprint(), len()

10.3 Proper Use of global and nonlocal

When to use global
  • When managing constants or configuration values
  • When multiple functions need to share a common variable
When to use nonlocal
  • When you need to modify a variable from an outer function inside a nested function

10.4 Best Practices for Scope Management

Minimize the use of global variables and favor local variables.When sharing data between functions, use arguments and return values—this is the best practice.Understand the scope rules (LEGB) and be aware of the variable lookup order.

10.5 Final Thoughts

A correct understanding and management of scopes is essential for improving your Python programming skills. In particular, being mindful to “avoid abusing global variables” and “clearly define function scopes” leads to better code. Master Python scopes and aim to write safer, more maintainable code! 🚀