0
0
Pythonprogramming~5 mins

Enclosing scope in Python

Choose your learning style9 modes available
Introduction
Enclosing scope helps a function remember variables from the function that contains it. This lets you use those variables inside the smaller function without passing them again.
When you want a small function inside another function to use some variables from the bigger function.
When you want to keep some data private inside a function but still use it in smaller helper functions.
When you want to organize your code by putting related functions inside each other.
When you want to create a function that remembers some settings or values from where it was created.
Syntax
Python
def outer_function():
    x = 10  # variable in outer function
    def inner_function():
        print(x)  # uses variable from outer function
    inner_function()
The inner function can use variables from the outer function without needing them as parameters.
This is called the 'enclosing scope' because the outer function's variables surround the inner function.
Examples
The inner function say_hello uses the message variable from greet.
Python
def greet():
    message = 'Hello'
    def say_hello():
        print(message)
    say_hello()
Using 'nonlocal' lets the inner function change the outer variable.
Python
def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        print(count)
    increment()
    increment()
Sample Program
The inner function prints the variable from the outer function's scope.
Python
def outer():
    text = 'Hi there'
    def inner():
        print(text)
    inner()

outer()
OutputSuccess
Important Notes
If you want to change a variable from the outer function inside the inner function, use the 'nonlocal' keyword.
Without 'nonlocal', assigning to a variable inside the inner function creates a new local variable instead of changing the outer one.
Enclosing scope helps keep your code organized and avoids using global variables.
Summary
Enclosing scope means inner functions can use variables from outer functions.
This helps keep data private and code organized.
Use 'nonlocal' if you want to change outer variables inside inner functions.