Scope of Variable: Python's Variable Potential

Everything has a scope in this world and not all will be useful everywhere. Each has a particular area where it can shine the brightest. This is applicable to humans, animals, and even to coding as well. Feeling confused? Don't worry, what I mean by that is every code has a specific scope that can only work best under certain conditions.

You have learned about variables in Python in the previous article and how much impact it has on Python code. Combining this with the concept that I mentioned above, you are going to learn about the scope of variables in Python in this article. It is very important for you to learn this concept as it can help you decide which variables to use according to the situation to make the code more efficient and visible so without further ado, let's get started.

Scope of Variable in Python:

In Python, the scope of a variable refers to the region of the program where the variable is recognized and can be accessed. The scope determines the visibility and lifetime of a variable within the program.

It is very important to understand the scope of variables in order to write structured and maintainable code. Python offers various scopes for variables that include global, local, enclosing (non-local), and class scopes. Let us learn more about this in the upcoming section.

Types of Variable Scopes in Python:

As discussed previously, variable scopes in Python are inclusive of four types:

  1. Global Scope: Variables that are defined outside of any function or class have global scope. This means they can be accessed from anywhere within the program. Global variables are typically declared at the top level of a module or script. Here's an example:
 >>> x = 10 # Global variable
 >>> def my_function():
 >>>     print(x) # Accessing global variable
 >>> my_function()
Output:

10

In the above example, the variable 'x' is defined outside the function, so it has global scope. It can be accessed inside the 'my_function()' because it is visible within the entire program.

  1. Local Scope: Variables defined inside a function have local scope. They are accessible only within that function and are not visible outside of it. Each function call creates a new instance of the local variables, and their values are independent of each other. Here's an example:
 >>> def my_function():
 >>>     y = 20 # Local variable
 >>>     print(y) # Accessing local variable
 >>> my_function() # Output: 20
 >>> print(y) # Error: NameError: name 'y' is not defined

In the above example, the variable 'y' is defined inside the 'my_function()', so it has local scope. It can be accessed within the function, but if we try to access it outside the function, a 'NameError' will be raised because 'y' is not defined in the global scope.

  1. Enclosing Scope (Nonlocal): In Python, if a variable is defined in an enclosing (outer) function and accessed in an inner function, it is referred to as an enclosing or nonlocal variable. The variable can be accessed within the inner function but is not visible outside of it or in other sibling functions. Here's an example:
 >>> def outer_function():
 >>>     z = 30 # Enclosing variable
 >>>     def inner_function():
 >>>        print(z) # Accessing enclosing variable
 >>>     inner_function()
 >>> outer_function() # Output: 30
 >>> print(z) # Error: NameError: name 'z' is not defined

In the above example, the variable 'z' is defined in the 'outer_function()', and it is accessed in the 'inner_function()'. The variable 'z' has an enclosing scope within the 'inner_function()'.

  1. Class Scope: Variables defined within a class, but not inside any class methods, have class scope. They are accessible within the class and can be accessed using the class name or instance of the class. Here's an example:
 >>> class MyClass:
 >>>     class_var = 40 # Class variable
 >>>     def my_method(self):
 >>>         print(MyClass.class_var) # Accessing class variable
 >>> obj = MyClass()
 >>> print(obj.class_var) # Accessing class variable using instance
 >>> obj.my_method()
Output:

40

In the above example, the variable 'class_var' is defined within the 'MyClass' class. It has a class scope and can be accessed using the class name 'MyClass' or an instance of the class 'obj'. Class variables are shared among all instances of the class

NOTE: It's important to note that if a variable is assigned a value within a function or method, Python treats it as a local variable by default. If you want to access a variable from an outer (non-local) scope within a function or method, you can use the 'globaL' or 'nonlocal' keywords to explicitly declare it.

Concluding Thoughts:

In conclusion, By leveraging the appropriate variable scopes, you, as a programmer can enhance code modularity and maintainability. Being mindful of variable scope enables you to create efficient and robust Python programs.

I hope you understood this concept clearly, practice it again and again to get a grip on it and over time, you will get to know what type of scope suits best for a particular scenario. If you have any questions regarding the topic, feel free to contact us.


Learn via Video Course

Python Logo

Python

6109

7 hrs