smartyfy.mrindigi.com

Python Master Course V2 — 055. Variable Scope and Lifetime

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 06 · LESSON 055 / 200

Variable Scope and Lifetime

Estimated study: 60–90 minutes. Prerequisite: Lesson 54, plus Python variables, collections, conditions and loops.

Course hub

Video lesson

Video not yet available. This is a reserved video link/player location.

Learning objectives

Distinguish local and global bindings. Explain the concepts in your own words, implement the pattern, predict output, test boundary conditions, and refactor for readability.

Concepts and professional approach

Distinguish local and global bindings. A function creates a reusable abstraction: it accepts inputs, performs a focused responsibility, and may return an output. Prefer small named functions with clear contracts. Validate external inputs at system boundaries, choose meaningful names, and separate calculation from printing so functions can be tested. Avoid hidden state where possible. Study the example, then change the inputs and explain the result.

Professional design checklist: define the purpose; choose inputs and outputs; consider invalid and edge-case values; write a minimal implementation; test normal, boundary and failure paths; then document the contract.

Understand and apply: Variable Scope and Lifetime

Scope answers where a name is found

A name is a binding to an object. Scope describes where Python can resolve that name, whereas lifetime describes how long the object remains available. They are related but different ideas. Each function call gets local bindings for its parameters and names assigned in its body. A module also has a global namespace. Using the same spelling locally does not automatically replace the module-level binding.

Python code

rate = 10

def calculate(value):
    rate = 3
    return value * rate

print(calculate(4))
print(rate)

Expected output

12
10

The local rate refers to 3 during the call, while the module-level rate still refers to 10. This is shadowing: a nearer binding is found before a farther one with the same name. For ordinary nested functions, remember LEGB: Local, Enclosing function scopes, Global module scope, then Builtins. This is a useful lookup model for these examples; class bodies and advanced constructs introduce additional details later.

Assignment changes how Python treats a name

If a function assigns to a name anywhere in its body, Python normally treats that name as local throughout the body, unless a global or nonlocal declaration says otherwise. Therefore reading it before its local assignment does not fall back to a similarly named global. This surprising error often appears when code tries to increment a global counter without declaring the intention.

Python code

count = 10

def broken_increment():
    count = count + 1
    return count

try:
    broken_increment()
except UnboundLocalError:
    print("count was read before its local assignment")

Expected output

count was read before its local assignment

The right side needs the local count before the left side has bound it. A cleaner repair is often def increment(count): return count + 1, with the caller storing the result. A global count declaration would instead direct assignments to the module namespace. It is legal, but introduces shared state and a dependency that is less obvious to callers.

Enclosing state and nonlocal

Python code

def make_counter():
    count = 0

    def next_value():
        nonlocal count
        count += 1
        return count

    return next_value

counter = make_counter()
print(counter())
print(counter())
other_counter = make_counter()
print(other_counter())

Expected output

1
2
1

The inner function keeps access to the enclosing binding after make_counter returns. nonlocal permits rebinding that existing enclosing name; it does not create a module global. Each call to make_counter establishes separate enclosing state. This pattern is called a closure. It is useful when a small operation deliberately carries state, but explicit arguments and results are often simpler for independent calculations.

An object may outlive the local name

Returning a list lets the caller keep a reference to it after the creating function has returned. Likewise, a closure can retain enclosing state. Avoid claiming that every local object is destroyed immediately at return: objects remain usable while reachable through references, and cleanup timing is not a scope guarantee. Mutating a passed-in list also differs from rebinding its local parameter; append changes the shared object, while assigning a new list only changes that local binding.

When refactoring a configuration-dependent calculation, change def cost(qty): return qty * PRICE into def cost(qty, price): return qty * price. Now each test can choose its own price without modifying shared module state. Keep meaningful constants global when appropriate, but make changing dependencies visible. Avoid local names such as list or sum when you still need the built-in objects they would shadow.

Progressive runnable Python example

Requires Python 3.10+. Save as lesson55.py, run with python lesson55.py or python3 lesson55.py.

rate = 10
def calculate(value):
    rate = 3
    return value * rate
print(calculate(5))
print(rate)

Expected output:

15
10

Additional exploration

Run the example with different valid inputs. Predict the result before executing. Extract repeated operations into a named function and write at least one assertion for the expected output. For invalid inputs, decide whether to return a documented result or raise an informative exception.

Guided practical project

Refactor a script to pass configuration rather than relying on globals. Start with a short requirements table identifying inputs, outputs and validation rules. Implement the smallest working function first, add a separate caller, and test at least three scenarios: typical input, boundary input and invalid input. Print a labeled report only at the program’s outermost layer.

Acceptance criteria: results are deterministic for the same inputs; no unexpected shared mutable state; invalid input is handled deliberately; output is documented; at least three assertions are included in your local project.

Common mistakes and debugging

  • Confusing print with return; printing does not pass a value back to the caller.
  • Using ambiguous names or overly long functions; divide responsibilities clearly.
  • Assuming all inputs are valid; validate values at appropriate boundaries.
  • Relying on global mutable variables; pass dependencies explicitly.
  • Skipping edge-case tests; test zero, empty, negative or missing values as applicable.

Practice and explained answers

Try each question before opening its answer. These self-checks do not record course completion.

Optional hint for question 1

The local assignment and the module-level assignment create distinct bindings.

1. Why does the first example print 12 and then 10?

Answer and reasoning: The call multiplies 4 by its local rate of 3. That assignment does not rebind the separate module-level rate, so the later print still displays 10.

2. Why is broken_increment an UnboundLocalError rather than a successful global update?

Answer and reasoning: Assignment makes count local throughout the function. Its right-hand side reads that local before it has a value. Pass count in and return the increment, or explicitly declare global state when that design is truly intended.

3. What does nonlocal count change in next_value?

Answer and reasoning: It directs assignments to the existing count binding in the enclosing make_counter call. Without it, the augmented assignment would try to read and write a new local count and fail before assignment.

4. Does returning a list destroy it when the function ends?

Answer and reasoning: No. The caller receives a reference to that list and can keep using it. The local binding ceasing to be directly accessible does not imply immediate destruction of the object.

5. Does calling items.append("x") require global items when items is a module-level list?

Answer and reasoning: No global declaration is needed merely to look up items and mutate the referenced list. Rebinding the name, as in items = [], is different. Even legal mutation of global objects creates shared state that should be documented or avoided.

Mastery checkpoint

Before moving on, explain the lesson concept, run the example, complete the project, write three tests, and explain why your function design is maintainable. The five-question self-check above provides answer explanations; it does not store account-level completion.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.