Technical Roadmap

Scope Python Variable

The scope of a variable is the specific area in your code where that variable can be accessed or "called." Outside of that area, the variable cannot be accessed as it is not alive there.

Asset

The Four Main Scopes in Python

Python follows the LEGB rule (Local, Enclosing, Global, Built-in) to determine where to look for a variable. Let's break down each one in detail:

1. What is a Local Scope?

A local variable is a variable that is defined inside a local scope, usually a function, and can only be accessed within that specific scope. If you declare a variable like x = 5 inside a function, you cannot use that variable outside of that function.

Below is a program to understand the local scope:

PYTHON
def my_function():
    # This is a local variable
    message = "I am local to this function"
    print(message)

# Calling the function
my_function()

# Trying to print the local variable outside the function
print(message)

Output

I am local to this function
NameError: name 'message' is not defined

Explanation:

In the above example, we defined a variable "message" inside a function def my_function(). Here the print() function prints the value of message inside the function, but when we try to print the value of message outside of it, it gives a NameError because the variable simply doesn't exist outside its local home.

2. What is an Enclosed Scope?

This is also called the Non-local Scope. This exists only inside a nested function-which is a function inside another function. The inner function can automatically access any variable defined in the outer function.

The Nonlocal Keyword

If the variable is a mutable object like a list, the inner function can modify its contents directly. However, it cannot modify any immutable objects like strings or numbers through simple assignment. To reassign or change these variables from inside the inner function, we must use the nonlocal keyword. This tells Python: "Don't create a new local variable; go up one level and use the one already in the outer function."

PYTHON
def outer_function():
    # Variable in the Enclosing Scope
    site_status = "Offline"
    print(f"Original Status: {site_status}")

    def inner_function():
        # Use nonlocal to modify the variable in the outer function
        nonlocal site_status
        site_status = "Online (Logicoria is Live!)"
        print(f"Inside Inner Function: {site_status}")

    inner_function()
    
    # Check if the change stuck
    print(f"Outside after inner call: {site_status}")

outer_function()

Output

Original Status: Offline
Inside Inner Function: Online (Logicoria is Live!)
Outside after inner call: Online (Logicoria is Live!)

Note: Our code editor does not support the nonlocal keyword. It is best to run this in a standard Python environment (IDLE, VS Code, or PyCharm).

Explanation:

In the above code, we have an outer function in which we defined a variable site_status that is local to it. The outer function encloses an inner function which is updating the value of the variable site_status, which is an immutable String. This update is only possible due to the nonlocal keyword. In the last line, when we call the outer function, we see that the site_status string has been successfully updated.

3. What is a Global Scope?

Global variables are defined at the very top level of your script, outside of any functions. They exist for the entire duration of the program and can be accessed from any part of the code. While you can read them anywhere, you cannot change them inside a function just by assigning a new value.

The Global Keyword

If you want to modify a global variable inside a function, you must use the global keyword. This tells Python that you are referring to the variable at the top level and not creating a new local one with the same name. Without this keyword, Python would just make a local copy and leave the global one unchanged.

Program to explain the global scope in Python:

PYTHON
# Create a global variable
message = "Welcome"

def display():
    global message
    message = "Welcome to Logicoria!"

# Run the function to trigger the change
display()

print(message)

Output

Welcome to Logicoria!

Explanation:

In the above program, we declared a global variable "message" outside of any functions at the top. Then we made a function display() in which we used the global keyword to modify the value of that global variable. Finally, we call the display() function and print the updated value of the global variable "message."

4. What is a Built-in Scope?

This is the widest scope in Python. It contains all the built-in functions, constants, and exceptions that come pre-installed with Python, such as print(), len(), type(), True, False, and None. All these names come from Python's internal module "builtins." You don't have to declare or import them; they have a universal scope, meaning they are available from everywhere in the program.

Related Topics

Scope in a Python Function and If-Else