Page Content

Tutorials

What Is Variable Scope In Python With Example 

Variable scope 

Variable Scope
Variable Scope

The area of a program where a variable scope is known and accessible is referred to as the variable scope in Python. The location of a variable’s assignment. Python applications are divided into distinct domains, or scopes, from one another.

There are different Variable scope they are, primarily local scope and global scope

  • A global variable is one that is defined outside of any functions in the main body of your code. Variable scope generated outside of a function are accessible from anywhere in the program and have global scope. The global scope is established at the start of your program and remains in place throughout its execution.
  • A variable that is defined inside a function is called a local variable. These variable scope are not visible or accessible outside of that function; they are scoped only to it. The lifespan of local variables is the duration of the function since they are created and deleted each time it is invoked.

Scopes might be compared to homes with tinted windows. When you are inside a home (local scope), you can see anything within; but, when you are outside a house (global scope or another local scope), you cannot see anything inside (local variables). On the other hand, one can frequently observe objects outside a house from within.

The LEGB Rule:

When a variable name without a dot, such as object. variable scope, is used inside a function, Python uses a particular search order to determine where the name is defined. The LEGB rule is the name given to this order.

The acronym LEGB represents the four scopes that Python searches, which are as follows:

Local (L): The current function or top level of a script is where Python first searches. The name is local if it is assigned inside the current def.

Enclosing (E): Python looks through the local scopes of any enclosing (or nested) functions if the name cannot be found locally. Later on, Python added this layer to manage variable scope in nested functions. Nestled functions are not local to references to names assigned in enclosing def lines.

Global (G): Python examines the global scope, the top level of the current module file, if the name is still not found. The entire file is affected by variable scope that are assigned outside of all defs. Every module has a distinct worldwide reach.

Built-in (B): Lastly, Python looks through the built-in scope, which has names like print, len, and keywords that have already been allocated in Python.

The moment Python discovers the name, it ceases its search. A NameError is raised if the name is not present in any of these scopes.

Code Example Illustrating Scopes:

Let’s look at a simple example:

# Global scope
g = 10 
print("1:", g) 
def fun():
    # Local scope of fun()
    g = 20 
    print("3:", g) 
g = 30 # This reassignment updates the global g 
print("2:", g) 
fun() 
print("4:", g) 

Running this code would produce the following output, demonstrating how different g variable scope are accessed based :

Output:

1: 10
2: 30
3: 20
4: 30
  • The first global g is printed in line 2.
  • The global g is updated to 30 on line 9.
  • Fun() is called in line 10. A new local variable called g is created inside fun() and given the value 20. This local g is accessed by the fun() function’s print(“3:”, g) instruction.
  • Line 11 brings the global scope back. Fun()’s local g is destroyed. The global g, which is still 30, is accessed once more by the print(“4:”, g) line.

The global Keyword:

Python automatically creates a local variable when you provide a value to a name inside a function. The global keyword must be used to explicitly declare a variable scope in the global scope if you wish to change it from within a function.

Code Example Using global:

# Global scope
value = 10 
print("In the global scope, value has been set to:", value, "\n")
def change global():
    # Local scope
    global value 
    value = -10 
    print("From inside the local scope of change global(), value is:", value) 
def shadow global():
    # Local scope
    value = -10 
    print("From inside the local scope of shadow global(), value is:", value)
change global() # Modifies the global value
print("In the global scope after change global(), value is:", value, "\n")
shadow global() # Creates and modifies a local value, global value is unaffected
print("In the global scope after shadow global(), value is:", value, "\n")

Output:

In the global scope, value has been set to: 10
From inside the local scope of change global(), value is: -10
In the global scope after change global(), value is: -10
From inside the local scope of shadow global(), value is: -10
In the global scope after shadow global(), value is: -10

As can be seen, the global declaration allowed change global() to successfully alter the global value. Without the global declaration, shadow global() produced a distinct local variable, but the global value remained the same.

Minimizing Global Variables

It is usually accepted as good programming practice to minimise the usage of global variables, especially as programs get larger, even if they are permitted and can be helpful in small programs or for central data structures that are accessed by multiple functions. Since local names are typically the best option, they are assigned by default in a def.

Here’s why it’s advised to minimise global variables:

Debugging Difficulty: If a global variable has an incorrect value, the bug could be anywhere in the extensive program that makes the change. Any issue affecting local variables and parameters must be contained within the function itself if it only uses them, which makes it simpler to find.


Increased Coupling: When functions alter global variables, they become dependant on them and maybe other functions that depend on them as well. Because of this, functions become less self-contained and are more difficult to reuse or alter separately.

Readability and Understanding: Because you have to follow the control flow across the entire program to determine the state of a global variable, programs that rely heavily on them may be more difficult for humans to comprehend. When analysing a function that makes use of a global variable, you must look beyond the function to comprehend its purpose, its assignment, and its potential changes.

Potential for Name Clashes: Although scope restrictions keep local variables from conflicting with globals or locals in other functions (unless they are purposefully used), excessive global usage raises the possibility of inadvertent global name conflicts, which can lead to jumbled code.

In general, it is preferable to utilise arguments for inputs and return values for outputs rather than global variables for inputs/outputs or for communication between functions. Functions become more autonomous and predictable as a result.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index