Sobes.tech
Junior — Middle

What is the role of closures in programming and what are they used for?

sobes.tech AI

Answer from AI

Closures in Python are functions that remember the environment in which they were created, including the values of variables from external scopes. They allow maintaining state between function calls without using global variables.

Main applications of closures:

  • Encapsulation of state
  • Creating function factories
  • Simplifying code when you need to preserve context

Example:

def make_multiplier(factor):
    def multiplier(number):
        return number * factor
    return multiplier

times3 = make_multiplier(3)
print(times3(10))  # Outputs 30

Here, multiplier is a closure that remembers the value of factor from the outer function.