Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is scope in Python

Understanding Scope in Python

When you're learning programming, it's like learning the rules of how a new world operates. In this world, the concept of "scope" is vital to understand. Imagine scope as the area in your house where certain rules apply. In the kitchen, for instance, the rule might be "wash your hands before cooking." Similarly, in programming, scope refers to the region of your code where variables are recognized and accessible.

The Basics of Scope

In Python, scope is determined by where you declare a variable. There are four types of scope:

Local Scope: Think of this as your bedroom. Variables declared inside a function are like your personal belongings kept in your bedroom. They are only accessible to you, or in the case of Python, to the function in which they are declared.

Enclosing Scope: This is like the living room, shared with your family. It's the scope of the outer function when you have a function inside a function (nested functions). The inner function can access variables from the outer function, just as you can use the TV in the living room.

Global Scope: Imagine this as your entire home. Variables declared at the top-level of your Python script are like the common rules that apply to the whole household. They are accessible from anywhere in the script.

Built-in Scope: This is like the laws of your country. Just as you don't need to define gravity for it to work, Python has a set of built-in functions and variables that are always available without any declaration.

Local Scope in Action

Let's look at a simple example to understand local scope:

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

greet()

In this example, the variable message is defined within the function greet(). It exists only in the local scope of the function. If you try to print message outside of the function, you'll get an error because message is not recognized outside its local scope.

print(message)  # This will cause an error.

Enclosing Scope Explained

Now, let's dive into an example of enclosing scope:

def outer_function():
    teacher = "Guido"

    def inner_function():
        student = "You"
        print("Teacher:", teacher)
        print("Student:", student)

    inner_function()

outer_function()

In this scenario, teacher is in the enclosing scope of inner_function(). The inner function can access teacher, but if you try to access student from the outer function, you'll get an error because student is in the local scope of inner_function().

Global Scope and How to Use It

Here's an example of using a global variable:

teacher = "Guido"

def greet_student():
    print("Your teacher is", teacher)

greet_student()
print("Global teacher:", teacher)

In this case, teacher is a global variable accessible both inside the function greet_student() and outside of it. But be cautious with global variables; overusing them can make your code hard to understand and maintain.

Built-in Scope: Python's Gift to Programmers

Python provides many built-in functions and variables that you can use without declaring them first. For example:

print(len("Hello"))  # len is a built-in function.

The len function is part of Python's built-in scope and can be used anywhere in your code.

Modifying Global Variables Inside a Function

What if you want to change a global variable inside a function? You can use the global keyword:

counter = 0

def update_counter():
    global counter
    counter += 1

update_counter()
print("Counter is now", counter)

By declaring counter as global within update_counter, you tell Python to use the global counter variable instead of creating a new local one.

Scope Best Practices

It's a good practice to limit the use of global variables. If you find yourself using them often, consider if there's a better way to structure your code. It's usually better to pass variables as arguments to functions and return results instead.

Analogies to Help You Remember

Think of scope like a set of nesting dolls. The smallest doll is local scope, contained within the next larger doll, the enclosing scope, and so on until the largest doll, which is the built-in scope. Each doll can see inside itself and any smaller dolls nested within, but not into the larger dolls enclosing it.

Conclusion: The World of Scope

Mastering the concept of scope is like learning the layout of a new city. It takes time, but once you understand which areas (scopes) have which rules (accessibility of variables), you'll navigate your code with confidence. Just as a city has different zones for residential, commercial, and industrial activities, your code has different scopes for variables. Use them wisely, keep your "city" well-organized, and you'll build a robust foundation for your programming journey. Remember, the best way to get comfortable with scope is to practice, so don't hesitate to experiment with your own code examples. Happy coding!