Basics
Python Scope
Python Variable Scope
Python scope follows LEGB, with global and nonlocal keywords.
Introduction to Python Scope
In Python, scope refers to the region of the code where a variable is accessible. Understanding scope is crucial for writing efficient and bug-free code. Python uses the LEGB rule to determine the scope of a variable, which stands for Local, Enclosing, Global, and Built-in. Additionally, Python provides global and nonlocal keywords to modify the scope of variables.
The LEGB Rule Explained
Python determines the scope of a variable using the LEGB rule. Here's what each level stands for:
- Local: Refers to variables defined within a function.
- Enclosing: Refers to variables in the local scope of enclosing functions in nested functions.
- Global: Refers to variables defined at the top level of a module or script.
- Built-in: Refers to special variables that are part of Python's built-in module.
Local Scope
Variables defined inside a function belong to the local scope of that function and cannot be accessed outside it. This behavior helps in preventing accidental modifications of variables.
Enclosing Scope
Enclosing scope comes into play in nested functions, where an inner function can access variables from its enclosing function but not modify them unless the nonlocal keyword is used.
Global Scope
A variable declared outside a function belongs to the global scope and can be accessed inside functions. However, to modify a global variable inside a function, you must use the global keyword.
Built-in Scope
The built-in scope includes Python's built-in functions and exceptions. These are always available and have the lowest priority in the scope resolution process.
Using the Global Keyword
The global keyword allows you to modify a variable that is in the global scope. This is useful when you need to update a global variable from within a function.
Using the Nonlocal Keyword
The nonlocal keyword is used to modify a variable in the enclosing scope, which is not the global scope. This is particularly useful in nested functions.
Basics
- Introduction
- Installation
- Running Code
- Syntax
- Variables
- Data Types
- Numbers
- Strings
- Booleans
- Type Conversion
- Operators
- Ternary Operator
- If Else
- Match Case
- While Loops
- For Loops
- Lists
- Tuples
- Dictionaries
- Sets
- Comprehensions
- Functions
- Arguments
- Scope
- Errors
- Debugging
- String Formatting
- Security Basics
- Best Practices
- User Input
- Built-in Functions
- Keywords