Python Scope Rules Tutorial – Complete Guide

Python is a robust language widely used in the world of coding and development. It’s simple yet powerful, offering a straightforward syntax coupled with a plethora of powerful features. Python’s scope rules are part of what makes this language so versatile and easy to use. But what exactly are these scope rules and why are they important to learn?

Understanding Python’s Scope Rules

Python’s scope rules pertain to namespace, a container where names are mapped to objects. When you create a variable in Python, you’re essentially adding a name into the namespace. Understanding these rules helps us to manage these names effectively, avoiding potential conflicts and errors in our code.

Understanding scope rules promotes clean and efficient coding. Avoided are the messy and confusing scenarios where variables interact in ways they shouldn’t be. Future debugging is also simplified as we can pinpoint where each variable comes from and how they should interact. Essentially, learning the scope rules makes you a more effective and efficient Python coder.

Next, we will dive right into the coding tutorial where we will explore Python’s scope rules with an uncomplicated game analogy. Let’s start!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Python’s Scope Categories

Python’s scope is divided into four categories: Built-in (B), Global (G), Enclosing (E) and Local (L), this is also known as the LEGB rule. These categories help determine where we can access a variable in our code. Let’s illustrate with examples.

Example 1 – Built-in and Global Scope

Built-in names are loaded by Python when it starts running a program. They exist in Python’s built-in namespace and can be accessed from anywhere in your code. Global names, on theother hand, are loaded when the module is imported and they exist in the module’s global namespace. Any function or object within the module can access them.

# Built-in scope
print(dir(__builtins__))

# Global scope
x = 10
def example():
    print(x)
example()

Example 2 – Local Scope

Local names are newly declared within a function and exist in the function’s local namespace. They have local scope, meaning they can only be accessed within the limited scope of their function.

def example2():
    local_variable = 'Hello, Zenva!'
    print(local_variable)
example2() 

# This will lead to an error
# print(local_variable)

Example 3 – Enclosing Scope

Enclosing names are part of a function nested in another function (outer function). Their scope is within the outer function, but they can be accessed by any function nested within.

def outer_function():
    enclosing_var = 'Hi, Team Zenva!'
    def inner_function():
        print(enclosing_var)
    inner_function()
outer_function()

# This will give an error
# print(enclosing_var)

Python’s Scope Resolution

Python resolves names using the LEGB rule. It first looks up the name in the Local scope. If it’s not there, Python checks the Enclosing scope. Still not found? It then checks the Global scope, followed by the Built-in scope. Let’s understand these principles through examples.

Example 4 – Name Resolution

x = 'global' # Global scope

def outer():
    x = 'enclosing outer' # Enclosing scope

    def inner():
        x = 'local' # Local scope
        print(x)

    inner()

outer()

Example 5 – Global Keyword

In Python, global variables can be read from a local scope. However, if we want to write to them, we must declare them as global using the ‘global’ keyword.

x = 'Zenva is awesome!' # Global variable

def example5():
    global x
    x = 'Zenva is still awesome!' # Modifying global variable

example5()
print(x)

Example 6 – Nonlocal Keyword

The ‘nonlocal’ keyword in Python is used to work with variables in the nearest enclosing scope that’s not global.

def outer():
    x = "outer X"
    def inner():
        nonlocal x
        x = "inner X"
    inner()
    print(x)

outer()

We hope these examples help you understand the importance of Python’s scope rules and how to effectively use the LEGB rule in your coding journey. As always, happy coding!

Further Exploration of Python’s Scope Rules

Now that you have gotten a feel for Python’s scope rules, it’s time to drive into more complex and interesting examples. Remember, the goal here is not simply to understand the rules, but to master them. Let’s get started!

Example 7 – Reiterating the LEGB Rule

Understanding and remembering the LEGB rule is crucial. Here’s an example to help reinforce what you’ve learned.

a_var = 'global variable'

def a_func():
    print(a_var, '[ a_var inside a_func() ]')

a_func()
print(a_var, '[ a_var outside a_func() ]')

This code will work as expected, printing the global variable twice. Python finds the variable in the global scope because it’s not found in the local one.

Example 8 – The global Keyword

The ‘global’ keyword gives a variable global scope, meaning it’s accessible throughout the code – not limited to a single function.

def a_func():
    global new_var
    new_var = "I'm a global variable!"

a_func()
print(new_var)

Using the global keyword inside a function makes new_var accessible globally. Despite being defined inside the function, it’s also accessible from outside.

Example 9 – Local Variables Supercede Global

What happens when you have a global variable and a local variable with the same name? Local scope wins.

x = "I'm global"

def ex_func():
    x = "I'm local"
    print(x)

ex_func()
print(x)

The function ex_func() creates its own local x and changes its value. However, the global x remains unchanged.

Example 10 – Non-local Variables

The keyword ‘nonlocal’ inside a nested function alters the value of a variable defined in the nearest non-global scope.

def outer():
    x = "outer"

    def inner():
        nonlocal x
        x = "inner"
        print("Inside inner:", x)

    inner()
    print("Inside outer:", x)

outer()

The inner function modifies the x variable in the outer function, thus we see ‘inner’ printed in both cases.

Example 11 – Editing Collections

Interesting to note, is that collections (lists or dictionaries) can be modified inside a function even if it’s in the global scope.

numbers = [1, 2, 3]

def edit_numbers():
    numbers.append(4)

edit_numbers()
print(numbers)

Adding a number to the list numbers is allowed, even though it wasn’t declared as a global variable in the function. This is because lists are mutable and can be changed in-place.

Where to Go Next

Having grasped Python’s scope rules, the next logical step is to continue strengthening your Python coding abilities. By consolidating your understanding of these foundational concepts, you are significantly augmenting your potential to create impressive and efficient software.

There’s no better place to advance your Python journey than our Python Mini-Degree, an extensive collection of curated Python courses. This Mini-Degree affords you the opportunity to learn Python programming, covering a variety of vital topics, such as:

  • Coding basics and Algorithms
  • Object-Oriented Programming
  • Game and App Development

Your learning journey will be speckled with exciting projects, from creating arcade games and a medical diagnosis bot to making an escape room!

Python is a highly sought-after language in up and coming fields, such as data science, machine learning, and robotics. Our instructors are experienced and certified, and the course content includes interactive lessons, quizzes, and coding challenges. This helps consolidate your learning and allows you to fully immerse yourself in Python programming.

By the end of our Python Mini-Degree, you’ll have assembled an impressive portfolio of Python projects to showcase your newfound skills. This can open doors to numerous career opportunities in high-demand industries like data science and game development. Plus, our courses are regularly updated to ensure they remain current and continue to provide the most valuable learning experience.

For those seeking a more expansive collection of Python resources, don’t hesitate to explore our broader Python courses. Whether you’re solidifying the pylons of your Python foundation or reaching towards high levels of mastery, Zenva is with you every step of the way.

Conclusion

Python’s scope rules are fundamental to writing effective, efficient, and clean codes. A profound understanding of these principles elevates you as a developer, allowing you to capitalize on Python’s power to create remarkable software, apps, games, or AI systems. With the sound foundation you’ve built so far, the sky’s the limit!

At Zenva, we’re committed to equipping you with top-notch learning resources that guide you towards your coding goals. Whether you’re just starting out or ready to level up, dive into our Python Mini-Degree to continue your programming journey. As always, happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.