In Computer Programming, the scope of a name binding — an association of a name to an entity, such as a variable — is the region of a computer program where the binding is valid:where the name can be used to refer to the entity. Such a region is referred to as a scope block.
Scope (computer science)
In computer programming, the scope of a name binding-an association of a name to an entity, such as a variable-is the…
So, the above definition may be a little hard to depict, so lets examine what that means in reference to python and its own Scope
There are four Scopes in Python:
1. Local — Inside the current function
2. Enclosing — Inside enclosing functions
3. Global — At the top level of the module
4. Build In — the special builtins module
This is the code block or body of any Python Function
These are the questions you should probably be asking yourself right now:
1. How is
2. How is
Lets break down each line step by step:
line 1: We declare a variable
line 3: we create a function called
line 7: we call
- Whenever we call a function, we create a new
execution contextor new
scope block— So we are now back to
line 4: we are in a brand new execution context and create an integer and assign
xto the reference of that integer, we currently have no idea there is also a global
x. This is also referred to as
line 5: We call the
local_scope_example, it finds x so it prints
100. It’s very important to remember if there was no variable named
local_scope_examplepython would have jumped to the next
Scopewhich in this case is
Line 8:We jump back out to
GlobalScope and call the
xwhich is located on
line 1and prints
100. It’s important to remember here that python always goes inside out, so it never jumps inside
local_scope_exampleand thus never knows
xwas over written.
Phew! That was tedious but also crucial in understanding how
Scope Binding works in Python. We can apply this same exact knowledge to every other
This is a special scope that only exists for nested functions. The enclosing scope is the scope of the outer or enclosing function.
This is the top most scope. Names in this scope are visible from everywhere in your code.
This scope contains names such as keywords, functions, exceptions, and other attributes that are built into Python.
We have gone over the four scopes in python, Local, Enclosing, Global, Built-in. We also discussed how each scope checks itself to see if it can satisfy the requirements it needs and if it cannot then it checks the scope above it and continues in this fashion until the variable is found. If the variable is never found, an error is thrown.
I hope This has been helpful for you in understanding how scopes work! Happy Coding.