top of page
Search
Writer's pictureMayuri Kale

The LEGB Rule for Python Scope




Scope of variable refers to the portion of the program, where it's accessible, i.e., region where you can apply ( operate).


Local variable is a variable that's described in a function and global variable is a variable that's defined outside any function or class i.e. in

global space. Global variable is available in any function and local variable has scope simply in the function it's defined.

Applying the LEGB Rule for Python Scope


Python resolves names utilizing the so- called LEGB rule, which is named after the Python scope for names. The letters in LEGB stand for Local, Enclosing, Global, and Built-in. Then’s a quick overview of what these terms express

· Local (or function) scope is the code block or body of any Python function or lambda formulation. This Python scope contains the names that you define inside the function. These names will only be visual from the code of the function.


· Enclosing( or nonlocal) scope is a unique compass that exclusively exists for nested functions. However, also the enclosing scope is the scope of the external or enclosing function, If the local scope is an interior or nested function.


· Global (or module) scope is the top-most scope in a Python program, script, or module. This Python scope contains all of the names that you define at the top position of a program or a module.


· Built- in scope is a singular Python scope that’s created or loaded whenever you run a script or open an interactive session.



Conclusion


In this blog, we learned about scope of variable and LEGB Rule for Python Scope .


Python variables explain in functions aren't accessible outside of functions, unless they're fixed to an object affordable outside of the function. You can also check how python access variable outside function in our blog.

5 views0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page