28. Nested Functions and Nonlocal variables

Quiz: 0/5

Nested functions and nonlocal variables are powerful concepts in Python that allow you to manage variable scope effectively. Mastering these concepts is essential for writing cleaner, modular, and more structured code.

Nested Functions

A nested function is a function defined inside another function. The inner function has access to variables from the outer function's scope but maintains its own local scope.

Example: Using nested functions

def outer_function():
    outer_variable = "I'm from the outer function!"

    def inner_function():
        print(outer_variable)  # Accessing the outer function's variable

    inner_function()  # Calling the inner function

outer_function()  # Output: I'm from the outer function!

Key points:

  • inner_function() is defined inside outer_function().
  • The inner function can access variables from the outer function's scope, such as outer_variable.
  • However, variables defined in inner_function()are local to it and cannot be accessed by the outer function.

Nonlocal variables

Sometimes, you might need to modify a variable from an enclosing (outer) function's scope within a nested function. This is where the nonlocal keyword comes into play.

The nonlocal keyword tells Python to search for a variable in the nearest enclosing scope that is not global.

Example: Modifying outer variables with nonlocal

def outer_function():
    count = 0  # Variable in the outer function

    def inner_function():
        nonlocal count  # Declare that we want to modify the outer variable
        count += 1
        print(count)

    inner_function()  # Output: 1
    inner_function()  # Output: 2

outer_function()

Key points:

  • count is defined in the outer_function().
  • The nonlocal keyword allows the inner function to modify the count variable from the outer scope.
  • Each time inner_function() is called, it increments the count variable.

Why use nested functions and nonlocal?

Nested functions and nonlocal variables are especially useful for:

  • Encapsulation: Keeping helper functions private to their enclosing function.
  • State Management: Preserving and modifying state across multiple calls to a nested function.
  • Modular Code: Breaking down complex logic into smaller, manageable units.

Summary

  • Nested Functions: Let you define a function inside another function, with access to variables in the outer scope.
  • Nonlocal Variables: Allow you to modify variables from the outer function's scope within a nested function.

By using these features, you can write more modular and efficient code while maintaining proper control over variable scope. These concepts are particularly valuable in scenarios involving closures, decorators, or stateful functions.

Hands-On Practise

Exercise: Counter function

Write a function called counter that contains a nested function increment.

  • The counter function should initialize a variable count to 0.
  • The increment function should use the nonlocal keyword to modify count and increase its value by 1 each time it’s called.
  • The counter function should return the increment function.

Example:

my_counter = counter()
print(my_counter())  # Output: 1
print(my_counter())  # Output: 2
print(my_counter())  # Output: 3
Output:

Quizzes: 0/5

Question 1:

What is a nested function in Python?

  • A function that calls itself.
  • A function defined inside another function.
  • A function that modifies global variables.
  • A function with no arguments.

Question 2:

What does the nonlocal keyword do in Python?

  • Allows access to variables in the global scope.
  • Declares a variable as constant in a function.
  • Allows a nested function to modify a variable in the enclosing function's scope.
  • Creates a new variable in the local scope.

Question 3:

Which statement is TRUE about nested functions in Python?

  • Nested functions cannot access variables from their enclosing function.
  • Nested functions have their own local scope.
  • Nested functions can modify variables in the global scope without a keyword.
  • Nested functions are always recursive.

Question 4:

What will the following code output? `python def outer(): x = 10 def inner(): nonlocal x x += 5 print(x) inner() outer() `

  • 5
  • 10
  • 15
  • Error

Question 5:

Which of the following requires the use of the nonlocal keyword?

  • Accessing a variable from an enclosing function.
  • Modifying a variable in the global scope.
  • Modifying a variable in an enclosing function's scope.
  • Defining a nested function.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonUnderstanding the global KeywordNext lessonUsing the return statement in Python Functions