Python's closure is a bit advanced concept that we may not directly use daily. But it is a very important concept that every Python developer needs to understand. Many key features in Python are built on the concept of closure, like Decorators.
But before we can understand the concept of closure, we must first understand the concept of nonlocal variables.
Let's take a look at an example below where we have a nested function.
We see that the sayHello() function does not have a local variable 'name', but it still refer to it. So, Python uses the variable 'name' in whatever next scope it can find, and that variable is considered as 'nonlocal' variable.
Let's see how it works when we can this function.
As we expect, every time the nonlocal variable changes value, the sayHello() function prints out the corresponding value.
Now the great() function has already finished and all of its local variables, including the variable 'name' which the sayHello() function refers to, are all gone. What happens if we invoke the function that has been assigned to the variable again.
Now, that's odd that the function somehow still 'remembers' and prints out the last value of variable name.
How did that happen?
Actually, that is closure in Python. When Python return the sayHello() function from the great() function, it does not only return the function itself but also return the function plus all associated nonlocal variable that the function refers.
This is a very important concept in Python that we need to understand to be able to use Python effectively.
Happy closuring!
Comentarios