Home > Backend Development > Python Tutorial > How Does Python's LEGB Rule Determine Variable Scope?

How Does Python's LEGB Rule Determine Variable Scope?

Barbara Streisand
Release: 2024-12-23 07:36:30
Original
660 people have browsed it

How Does Python's LEGB Rule Determine Variable Scope?

Python's LEGB Rule: Demystifying Scoping Rules

Python's scoping rules, often a source of confusion, can be readily apprehended through the LEGB rule.

LEGB Rule

The LEGB rule provides a clear algorithm for determining the availability of variables within a given scope:

  • L (Local): Variables defined within a function or lambda expression.
  • E (Enclosing-function): Variables defined in enclosing functions, from inner to outer.
  • G (Global): Variables defined at the module level or declared global within a function.
  • B (Built-in): Pre-assigned variables from Python's built-in names module.

Example

Consider the following code:

class Foo:
    def spam():
        for var in []:
            x()
Copy after login

Using the LEGB rule, we can determine the scope of the variable x:

  • L: None. x is not defined locally within the spam function.
  • E: None. The spam function is not nested within another function.
  • G: Yes. If x is defined at the module level, it will be available within the spam function.
  • B: Yes. If x is a built-in variable (e.g., a Python function), it will be accessible.

In this example, x would be found if it were defined at the module level or is a Python built-in.

The above is the detailed content of How Does Python's LEGB Rule Determine Variable Scope?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template