Before moving on to closure, we first need to understand nested functions and non-local variables.
Take a look at the code snippet below:
def main():message = "Hello World"def inner_main():print(message)inner_main()main()
Explanation
main()
function.main()
.inner_main()
. This nested function is able to access the message
that is not local to this function.inner_main()
function in our main()
function.main()
function and see the output as Hello World
. This confirms that nested functions can access the local variables of the outer functions.Now that we understand how nested functions work, we can understand the concept of closure. In line 7 in the code above, instead of calling the nested function, what would happen if we return the closure()
function?
Look at the code snippet below to understand this:
def main():message = "Hello World"def inner_main():print(message)return inner_mainclosure = main()closure()
Explanation
main()
function. Here, the returned function from main()
gets bound to the name closure
.main()
returned a function, we can call closure()
, and get the result from the nested function.Hence, we can define closure
as a function object that can remember the value in its scopes, even if they are not present in the memory.
This also means that you could delete the main()
function from memory and access the returned function.
Take a look at the code snippet below to understand better.
def main():message = "Hello World"def inner_main():print(message)return inner_mainclosure = main()del mainclosure()
Explanation
main()
function from the program memory, but we can still access the returned function. This is what This is a very tricky question as introducing too many nested functions can increase the complexity of the code. So, it is suggested to use closures when: