Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Scope: Where Variables Live | Namespaces, Scope, and Variable Resolution
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Internal Mechanics of Python Code Execution

bookScope: Where Variables Live

Understanding how Python finds and resolves variable names is essential for writing correct and bug-free code. The LEGB rule is at the heart of this process. LEGB stands for Local, Enclosing, Global, and Built-in, and it describes the order in which Python searches for a variable name when it is referenced in code.

  • Local: The innermost scope, usually within a function or method, where variables are defined by assignment;
  • Enclosing: Any enclosing function scopes, if the function is nested inside another function;
  • Global: The top-level scope of the module or script in which code is running;
  • Built-in: The special scope containing Python’s built-in names, such as len or range.

When you use a variable name, Python first looks in the local scope. If it is not found, it checks any enclosing scopes, then the global scope, and finally the built-in scope. This process ensures that variable names are resolved in a predictable way, even when functions are nested.

123456789101112131415
# Illustrating LEGB rule with nested functions def outer(): x = "enclosing" def inner(): x = "local" print("Inner:", x) # Local scope inner() print("Outer:", x) # Enclosing scope x = "global" outer() print("Global:", x) # Global scope print("Built-in:", len([1, 2, 3])) # Built-in scope
copy

Scope not only determines where you can access a variable, but also how long it lives and when it is destroyed. Variables defined inside a function exist only while the function runs; after that, they are gone. Variables in the global scope persist for the lifetime of the program. One common pitfall is accidentally modifying a variable in an unexpected scope, which can lead to bugs that are hard to trace.

If you assign to a variable inside a function, Python treats it as a local variable unless you explicitly declare it as global or nonlocal. This can cause confusion when a variable with the same name exists in an outer scope.

For instance, consider the following example where modifying a variable inside a nested function does not affect the variable in the enclosing scope unless you use the nonlocal or global keyword.

1234567891011
# Modifying variables in different scopes def counter(): count = 0 def increment(): count = count + 1 # UnboundLocalError: count referenced before assignment return count return increment # This will raise an error if you call counter() and then try to increment, # because 'count' is treated as a new local variable in increment(), not the enclosing one.
copy

1. What does the LEGB rule stand for?

2. How does Python resolve a variable name inside a nested function?

question mark

What does the LEGB rule stand for?

Select the correct answer

question mark

How does Python resolve a variable name inside a nested function?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 2

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

bookScope: Where Variables Live

Glissez pour afficher le menu

Understanding how Python finds and resolves variable names is essential for writing correct and bug-free code. The LEGB rule is at the heart of this process. LEGB stands for Local, Enclosing, Global, and Built-in, and it describes the order in which Python searches for a variable name when it is referenced in code.

  • Local: The innermost scope, usually within a function or method, where variables are defined by assignment;
  • Enclosing: Any enclosing function scopes, if the function is nested inside another function;
  • Global: The top-level scope of the module or script in which code is running;
  • Built-in: The special scope containing Python’s built-in names, such as len or range.

When you use a variable name, Python first looks in the local scope. If it is not found, it checks any enclosing scopes, then the global scope, and finally the built-in scope. This process ensures that variable names are resolved in a predictable way, even when functions are nested.

123456789101112131415
# Illustrating LEGB rule with nested functions def outer(): x = "enclosing" def inner(): x = "local" print("Inner:", x) # Local scope inner() print("Outer:", x) # Enclosing scope x = "global" outer() print("Global:", x) # Global scope print("Built-in:", len([1, 2, 3])) # Built-in scope
copy

Scope not only determines where you can access a variable, but also how long it lives and when it is destroyed. Variables defined inside a function exist only while the function runs; after that, they are gone. Variables in the global scope persist for the lifetime of the program. One common pitfall is accidentally modifying a variable in an unexpected scope, which can lead to bugs that are hard to trace.

If you assign to a variable inside a function, Python treats it as a local variable unless you explicitly declare it as global or nonlocal. This can cause confusion when a variable with the same name exists in an outer scope.

For instance, consider the following example where modifying a variable inside a nested function does not affect the variable in the enclosing scope unless you use the nonlocal or global keyword.

1234567891011
# Modifying variables in different scopes def counter(): count = 0 def increment(): count = count + 1 # UnboundLocalError: count referenced before assignment return count return increment # This will raise an error if you call counter() and then try to increment, # because 'count' is treated as a new local variable in increment(), not the enclosing one.
copy

1. What does the LEGB rule stand for?

2. How does Python resolve a variable name inside a nested function?

question mark

What does the LEGB rule stand for?

Select the correct answer

question mark

How does Python resolve a variable name inside a nested function?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 2
some-alt