Sobes.tech
Junior — Middle

In what ways are functions with preserved context created in Python, and how are they implemented?

sobes.tech AI

Answer from AI

In Python, functions with preserved context are usually created using closures and generator functions.

Closures are functions that "remember" the values of variables from the surrounding context, even if that context has already gone out of scope.

Example of a closure:

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

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

Here, the multiplier function retains the value of factor from the outer function.

You can also use objects with a __call__ method to preserve state.

class Multiplier:
    def __init__(self, factor):
        self.factor = factor
    def __call__(self, number):
        return number * self.factor

times3 = Multiplier(3)
print(times3(10))  # 30

Thus, closures and stateful objects allow for preserving context between function calls.

In what ways are functions with preserved context… - sobes.tech