LEGB rule in Python, clearly explained:
Every Python developer must know the LEGB rule!
It's crucial for avoiding major bugs!
And today, I will provide a clear explanation of the same!
Let's go! π
Let's start by understanding meaning of scopeβοΈ
The scope of a variable defines the area of a program from where you can access it.
The name will only be visible to and accessible by the code in its scope.
Here's an illustration of the same...π
1οΈβ£ Local Scope:
Local scope refers to variables defined within a function.
These variables are only accessible within the function where they are defined.
They are created at the function's call and destroyed when the function ends.
Example...π
2οΈβ£ Enclosing Scope:
Enclosing scope is relevant in the context of nested functions.
If a variable isn't in the local scope but is defined in an outer function, it's in the enclosing scope.
It is accessible from the inner function but not from the global scope!
Example...π
3οΈβ£ Global scope
Global scope encompasses variables defined at the top level of a script or a module.
Global variables are accessible from anywhere within the module or script, including inside any functions.
Created when the script starts and last until it ends.
Example...π
4οΈβ£ Built-in scope
Built-in scope includes names that are pre-defined in the Python language.
This scope contains functions like `print()`, ` len()`, and types like `int`, `float`, which are always available without the need for any imports.
Example ...π
What if scopes collideβ
When scopes collide in Python, the LEGB rule plays a crucial role in determining how variables are resolved.
Python always looks for a variable in the order:
Local β Enclosing β Global β Builtin
Here's a good example:
That's a wrap!
If you interested in:
- Python π
- ML/MLOps π
- CV/NLP π£
- LLMs π§
- AI Engineering βοΈ
Find me β @akshay_pachaar βοΈ
Everyday, I share tutorials on above topics!
Cheers!
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.
