Variable Scopes in Python

Python variable scope defines the visibility and accessibility of a variable within different parts of your program. Understanding scope rules is critical for writing clear, bug-free, and maintainable Python code.

In this tutorial, you’ll learn about:

  • Local Scope
  • Global Scope
  • Nonlocal Scope
  • Built-in Scope
  • Using keywords: global and nonlocal

What is Variable Scope?

The scope of a variable is the area of a program where the variable is recognized. Python has four main scopes:

  1. Local scope: Variables defined inside a function.
  2. Enclosing (nonlocal) scope: Variables defined in enclosing functions.
  3. Global scope: Variables defined at the top-level of a script or module.
  4. Built-in scope: Predefined Python variables, functions, and exceptions.

Python resolves variable names following the LEGB rule:
Local → Enclosing → Global → Built-in

1. Local Scope

A variable declared inside a function has a local scope. It can only be accessed within the function itself.

def greet():
    message = "Hello, Python!"
    print(message)

greet()        # Outputs: Hello, Python!
# print(message)  # Error: message is not defined

Here, message is a local variable. Attempting to access it outside its defining function raises a NameError.

2. Global Scope

A variable defined outside all functions has a global scope and is accessible anywhere within the file (including within functions).

language = "Python"  # Global variable

def greet():
    print("Hello,", language)

greet()         # Outputs: Hello, Python
print(language) # Outputs: Python

In this example, language is glModifying Global Variables with globalobal and accessible throughout the script.

Modifying Global Variables with global

If you need to modify a global variable within a function, use the global keyword.

count = 0  # Global variable

def increment():
    global count
    count += 1
    print("Inside function:", count)

increment()  # Outputs: Inside function: 1
print("Outside function:", count)  # Outputs: Outside function: 1

Without declaring global count, modifying count within the function would raise an error or create a local variable with the same name.

3. Nonlocal (Enclosing) Scope

Nested functions can access variables from their parent (enclosing) function’s scope.

def outer():
    msg = "Hi"

    def inner():
        print(msg)

    inner()

outer()  # Outputs: Hi

Here, msg is in the enclosing scope, accessible to the nested inner() function.

Modifying Nonlocal Variables with nonlocal

If you need to modify a variable from an enclosing function, use the nonlocal keyword.

def outer():
    number = 5

    def inner():
        nonlocal number
        number += 1
        print("Inner:", number)

    inner()  # Outputs: Inner: 6
    print("Outer:", number)  # Outputs: Outer: 6

outer()

The keyword nonlocal allows nested functions to modify variables defined in their enclosing scope.

4. Built-in Scope

Python has predefined variables, functions, and constants. They exist in the built-in scope and are available everywhere unless explicitly overridden.

Examples of built-in variables/functions:

  • print()
  • len()
  • sum()
my_list = [1, 2, 3]
print(len(my_list))  # Outputs: 3

Be careful not to override built-in names, as it may lead to confusing errors:

# Don't do this!
len = 5  # Overrides built-in len()

# Now, this will raise an error:
# print(len([1, 2, 3])) # TypeError: 'int' object is not callable

Scope Resolution (LEGB rule)

When resolving a variable name, Python searches scopes in this order:

  • Local: Inside the current function.
  • Enclosing: Inside enclosing functions.
  • Global: At the module/script level.
  • Built-in: In built-in Python namespace.
x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)  # Outputs: local

    inner()
    print(x)  # Outputs: enclosing

outer()
print(x)  # Outputs: global

Common Mistakes and Best Practices

Avoid Shadowing

Avoid shadowing global or built-in names. This helps prevent confusion:

# Bad practice:
list = [1, 2, 3]  # overrides built-in list

# Good practice:
my_list = [1, 2, 3]

Use global and nonlocal Wisely

Excessive use of global and nonlocal may make your code harder to read and debug. Limit their usage, and prefer passing arguments or returning values.

Summary of Scope Keywords

KeywordPurposeExample Usage
globalModify a global variable inside a functionglobal var_name
nonlocalModify an enclosing variable inside a nested functionnonlocal var_name

Understanding variable scopes is crucial for Python programmers. Remembering the LEGB rule and appropriately using global and nonlocal keywords will help you write clear and maintainable Python programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top