On this page

Scope & Lifetime

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Understanding Scope in Python​

Scope defines where a name (variable, function, or reference) is visible and accessible in a program. Python uses a well‑defined set of rules to determine how names are resolved. Understanding these rules is essential for writing predictable, maintainable functions.

Python follows the LEGB rule, which stands for:

When Python encounters a name, it searches these scopes in order.

Local Scope​

A local scope is created whenever a function is called. Variables assigned inside a function belong to this scope.


def compute():

    x = 10      # local variable

    return x * 2

Key characteristics:

Local scope prevents different parts of a program from interfering with each other.

Global Scope​

Names defined at the top level of a file belong to the global scope.


x = 5   # global variable



def show():

    print(x)

Functions can read global variables, but they cannot assign to them unless explicitly declared using global.


count = 0



def increment():

    global count

    count += 1

Using global is generally discouraged in modular programming because it makes code harder to reason about.

Enclosing Scope (for Nested Functions)​

When a function is defined inside another function, the inner function can access names from the enclosing scope.


def outer():

    message = "hello"



    def inner():

        print(message)   # from enclosing scope



    inner()

This enables patterns such as closures, where an inner function retains access to variables from its enclosing function even after the outer function has finished executing.

Built‑in Scope​

Python provides a set of built‑in names such as len, range, and print. These are always available unless shadowed by a local or global name.


len([1, 2, 3])   # built‑in function

Shadowing built‑ins is a common beginner mistake:


len = 10   # shadows built‑in len()

Avoid reusing built‑in names for variables.

Variable Lifetime​

Scope determines where a variable is visible; lifetime determines how long it exists.

Local Variable Lifetime​

A local variable exists only during the execution of its function.


def example():

    x = 10

    return x

After the function returns, x is destroyed.

Global Variable Lifetime​

A global variable exists for as long as the program is running.


counter = 0   # created when the module loads

Global variables persist until the program ends or the module is unloaded.

Enclosing Variable Lifetime​

Variables in enclosing scopes live as long as the outer function’s frame exists. If an inner function forms a closure, those variables may persist longer.


def outer():

    value = 42

    def inner():

        return value

    return inner

Here, value remains alive because inner retains a reference to it.

Name Resolution and the LEGB Rule in Practice​

Python resolves names by searching scopes in the following order:

  1. Local
  2. Enclosing
  3. Global
  4. Built‑in

Example:


x = "global"



def outer():

    x = "enclosing"

    def inner():

        x = "local"

        print(x)

    inner()



outer()

Output:


local

Python stops searching as soon as it finds a matching name.

Why Scope and Lifetime Matter​

Understanding scope and lifetime helps you:

Scope is one of the core concepts that separates beginner code from professional‑quality code.

Summary​

In this lesson, you learned how Python determines where names are visible and how long variables live. You now understand local, global, enclosing, and built‑in scopes, the LEGB resolution order, and how variable lifetime interacts with function execution. These concepts are essential for writing reliable, modular Python programs and for understanding more advanced function behavior in later lessons.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Arguments & Return Values

Next

Lambda Functions