Scope in Python

  • Last updated Apr 25, 2024

In Python, a scope refers to the region in your code where a particular variable or object is accessible. Scopes are essential for organizing and managing the visibility and lifetime of variables, functions, and other identifiers in your code.

Python has two main types of scopes:

  1. Local Scope:
  2. Variables defined within a function are considered to be in a local scope. They are only accessible within the function where they are defined. Once the function execution is complete, local variables typically go out of scope, and their values are no longer accessible.

    def my_function():
        x = 70  # x is in the local scope of my_function
        print(x)
    
    my_function()
    print(x)  # This would result in an error, as x is not defined in the global scope
  3. Global Scope:
  4. Variables defined outside of any function are in the global scope. They can be accessed from any part of your code, including inside functions, but you need to declare them as global if you want to modify them within a function.

    y = 40  # y is in the global scope
    
    def my_function():
        global y  # To modify the global variable y within the function
        y = 80
        print(y)
    
    my_function()
    print(y)  # This will print 80 as y has been modified in the function

    Python also supports nested functions. In this case, a variable can be in an enclosing scope if it's defined in an outer function and is accessible in an inner function. You can use the nonlocal keyword to modify non-local variables.

    Example:

    def outer_function():
        a = 60
    
        def inner_function():
            nonlocal a
            a = 90
            print(a)
    
        inner_function()
        print(a)  # This will print 90 as a has been modified in the inner_function
    
    outer_function()

It's important to understand the rules of variable scope in Python to avoid naming conflicts and to ensure that your code functions as expected. The scope of a variable determines where it can be accessed and whether it can be modified within your program.