Starting out as a newbie in programming learning python, variable scope seemed to be the trickiest of them bunch at the time, but are probably the simplest and easiest concept to get
Hence it is essential to understand the levels of scope in python and how things can be accessed from all the different scopes.
Well, lets just jump right into it. Scope refers to the area of the program where a variable or function is accessible, let's try this analogy here by going back to when you were 10 years of age, imagine you and your friends are playing with some toys in the room and Each of you has a box with your own toys, and you can only use the toys in your own box. That's like a scope in programming generally,
In python there are different types of scopes, Each scope is like a box or container with its own variables and rules. Variables and functions defined in one scope can only be used within that particular scope, and not in other scopes. This helps keep the code organized and prevents mistakes. There are generally 4 types of scopes in python:
- Local scope: They refer to the variable declared in the function alone. In the below code the var variable is only accessible to the code within the main_function function. Anything outside of this function will not be accessible.
def main_function(): var = 1 print(var) # prints the value 1 main_function() # Returns the value of function main which is 1 print(var) # Returns an error because it is outside the function
- Enclosed scope: Refers to the variables and functions that are defined within a function that is inside another function. In the code below, I added a nested function called inner_function to the outer_function function.
As inner_function is inside the scope for the outer_function function it can then access the variable. However, the enclosed variable inside the inner_function function cannot be accessed from inside the outer_function function.
def outer_function(x): #enclosed variable declared inside a function y = 10 def inner_function(z): return x + y + z return inner_function result = outer_function(5) print(result(6))
- Global scope: Its when a variable is declared outside of a function. This means it can be accessed from anywhere.
In the code below,
x = 10 # x is a global variable def multiply_by_2(): return x * 2 print(multiply_by_2()) # Output: 20
In this example, the variable x is defined in the global scope and can be accessed from within the function multiply_by_2(). The function returns x * 2, which is 20 in this case.
Built-in scope: Refers to the reserved keywords that Python uses for its built-in functions, also defined in the core Python language and are available for use without importing any module or library, such as
print, def, for, in,and so forth. Functions with built-in scope can be accessed at any level within the code.
Oldest comments (0)