Closure


In Python, we also have the concept of closure, which is represented here as nested functions. They are not allowed in C++, unless the inner function is anonymous, that is, a lambda expression. 

Basically, the closure is the set of variables that a function can see (defined variables). If the inner function needs it's own parameters to do its job, then it closes over itself. If it needs the outer function variables to do so, then the closure is over the surrounding context. 

Unlike C++, the risk of segmentation fault is somehow eliminated because in Python everything is an object, including functions. With that, we can return the inner function to the scope that called the outer function, for example. Looking at the behavior of the code lines made by PyLenin [1], even if the outer function is deleted, the inner function still remembers the last data passed to the outer function before being destroyed. Here is the code:

def number(x):
    def add(y):
        print(x+y)
    return add # don't use () or you will call the function, not return it.

result = number(100)
result(50)
delete number
result(100)

Why this would be necessary? The answer is you can use object oriented solutions without using a class and implement decorators [1] , which are a way to change function behavior without directly changing the function itself [2].

<- Back
Next ->

No comments:

Post a Comment

Global Game Jam 2024

Wow, what a weekend. The Global Game Jam is intense. But I and 3 other members manage to build a game for the theme "Make me laugh&quo...