Variable Scope and Lifetime
Explore how Python controls variable visibility and lifetime within different scopes such as local, global, and built-in. Understand how proper use of these scopes helps write reliable, maintainable functions and avoid common bugs caused by variable shadowing or misuse of global variables. Learn when and how to modify globals safely and why it is usually best to use function arguments and returns.
When we write small scripts, we often name variables without worrying much about where they "live." However, as our programs grow into multiple functions and modules, reuse of common identifiers such as data or count becomes unavoidable. If every variable were visible everywhere, these names would constantly overwrite each other, leading to subtle and hard-to-diagnose bugs.
Python solves this with scope, i.e., a set of rules that strictly controls where a variable can be accessed and modified. Understanding these rules allows us to write self-contained, reliable functions, ensuring that a computation in one part of our code doesn't accidentally alter values used elsewhere.
The concept of scope
Scope refers to the specific region of code where a variable name is recognized and associated with a value. It determines where that name can be accessed or modified during execution. Conceptually, scopes can be compared to isolated environments: operations within a given scope remain contained.
In Python, variables differ in visibility based on where they are defined. When a name is referenced, Python resolves it by searching through a well-defined hierarchy of scopes. In this lesson, we focus on the three most commonly encountered scopes: local, global, and built-in scopes.
Local scope and lifetime
A variable created inside a function exists in the local scope. It is visible only to code running within that specific function call.
This visibility is tied to the variable's lifetime, i.e., the ...