Scope In Python

Explore the essentials of Scope in Python: Learn about local, global, non-local, and built-in scopes to manage variables effectively in Python programming.

Scope in Python refers to the region in a program where a variable is recognized and accessible. Python utilizes two main types of scope: local and global. Local scope pertains to variables declared within a function, accessible only inside that function. Global scope, on the other hand, involves variables declared outside any function, making them accessible throughout the entire program.

In Python, when a function is called, a new local scope is created. Variables defined in this scope are not accessible outside the function. Conversely, variables in the global scope are accessible anywhere in the program, but modifying them within a function requires explicit declaration using the global keyword.

Python also adheres to the LEGB rule - Local, Enclosing, Global, Built-in - for name resolution. This means that when Python looks for a variable name, it first checks the local scope, then any enclosing scopes (like those in nested functions), the global scope, and finally the built-in scope. Understanding scope is essential for managing variable visibility and lifespan in Python programs.

Types Of Scope In Python

The 4 types of Scope in Python are discussed below with examples.

1. Local Scope

Local scope in Python refers to the visibility of variables that are defined within a function. Variables created inside a function exist only in the local scope of that function and are not accessible outside of it. This scope is created at the moment the function is called and is destroyed once the function execution is completed.

Consider the following code for example.

def my_function():
    local_variable = 10
    print(local_variable)

my_function()

In this example, local_variable is a local scope variable. Its scope is confined to the my_function block. The output of this code will be.

10

However, attempting to access local_variable outside my_function will result in an error. For instance.

print(local_variable) # This will raise an error

Attempting to execute this line of code will result in a NameError because local_variable does not exist outside the local scope of my_function.

2. Global Scope

Global scope in Python refers to the area of a program where a variable is accessible throughout the entire program, regardless of where it is declared. Variables defined at the top level of a script or outside of any function belong to the global scope. These variables can be accessed from any part of the program, including inside functions.

Example.

global_variable = "I am global"

def my_function():
    print(global_variable)

my_function()

In this example, global_variable is a global scope variable, accessible inside my_function. The output of this code will be.

I am global

However, modifying a global variable inside a function requires explicit declaration using the global keyword. Without this declaration, Python will treat it as a new local variable.

Example.

def modify_global():
    global global_variable
    global_variable = "Modified globally"

modify_global()
print(global_variable)

The output after calling modify_global will be.

Modified globally

This illustrates how global variables can be accessed and modified throughout the program, provided the proper global declaration is used within functions.

3. Non-Local Or Enclosing Scope

Non-local or enclosing scope in Python refers to the scope that exists within nested functions, where the inner function has access to the variables of the outer function. This type of scope becomes relevant in scenarios involving nested functions, where an inner function wants to access or modify a variable that is defined in the outer function.

Example.

def outer_function():
    outer_variable = "I am outside"

    def inner_function():
        print(outer_variable)

    inner_function()

outer_function()

In this code, outer_variable is in the enclosing scope of inner_function. The output will be.

I am outside

However, if the inner function needs to modify a variable from the outer function, the nonlocal keyword is used.

Example.

def outer_function():
    outer_variable = "Original"

    def inner_function():
        nonlocal outer_variable
        outer_variable = "Modified inside"

    inner_function()
    print(outer_variable)

outer_function()

After calling outer_function, the output will demonstrate the modification made by inner_function.

Modified inside

This example illustrates how the nonlocal keyword allows inner functions to modify variables from their enclosing scope, making non-local scope an essential concept in Python's scope management.

4. Built-in Scope

Built-in scope in Python refers to the scope that contains all of Python’s built-in functions, exceptions, and other objects. These are available in any part of your Python program, without any need for import statements or declarations. The built-in scope is the widest in Python and remains in existence for as long as the Python interpreter runs.

Consider the function len(), which is a built-in function, as an example.

print(len([10, 20, 30]))

Output.

3

Another example is the built-in exception ValueError.

try:
    int("abc")
except ValueError:
    print("Caught a ValueError!")

The output of this code, which attempts to convert a non-numeric string to an integer, will be.

Caught a ValueError!

In these examples, both len() and ValueError are accessed without any special import statements because they are part of Python's built-in scope. This scope includes a wide range of commonly used functions and exceptions, making them readily accessible in any Python program.

In conclusion, understanding the scope of Python is crucial for effective programming and managing variable visibility. Python's scope types - local, global, non-local (enclosing), and built-in - each serve distinct purposes in a program. Local scope confines variables within functions, ensuring encapsulation and preventing unintended interactions. Global scope allows for variables to be accessed throughout a program, while non-local scope facilitates variable access and modification in nested function scenarios. Finally, built-in scope provides a set of pre-defined functions and exceptions accessible anywhere in the program.

Mastering these scopes allows for cleaner, more efficient code, avoiding common pitfalls like variable shadowing or unintended modifications. By adhering to Python's scope rules and utilizing keywords like global and nonlocal appropriately, programmers can create more robust and error-free applications. In essence, a firm grasp of Python's scoping principles is a foundational skill for any Python programmer.

You can also check these blogs:

  1. Indentation In Python