In Python, the scope of a variable determines where that variable can be accessed or modified within the code. The concept of scope is crucial for writing understandable, maintainable, and bug-free code. This article explores the various scopes available in Python, including how variables behave when passed to functions.
Python primarily categorizes scope into four types, often remembered by the acronym LEGB:
A variable declared inside a function is local to that function. It can be accessed and modified only within the function where it is declared.
In the example above, local_var is only accessible within my_function().
This scope is relevant in nested functions. A variable declared in an enclosing function is accessible to any nested functions, but not outside the enclosing function.
Here, outer_var in outer_function can be accessed and modified by inner_function using the nonlocal keyword.
A variable declared outside any function or class has a global scope. It can be accessed and modified from anywhere in the module.
The global keyword allows a function to modify a global variable.
These are special reserved keywords in Python that are globally available. They are part of the built-in functions and variables provided by Python.
len is a built-in function, available without any import or declaration.
When you pass variables to a function, Python handles them differently based on their type:
When an immutable object is passed to a function, the function operates on a copy of the object. Changes within the function do not affect the original object.
In this case, a remains unchanged outside the function.
When a mutable object is passed to a function, the function can modify the original object.
The changes to my_list within modify_mutable persist outside the function.
Understanding variable scope is essential for effective programming in Python. It helps in avoiding conflicts, reducing bugs, and writing cleaner code. The four scopes (local, enclosing, global, and built-in) dictate the accessibility and lifespan of variables. Additionally, knowing how Python handles variables passed to functions (by value for immutables and by reference for mutables) allows you to manage data correctly across different parts of your code.