Python 101 : Closures

Closures are simply inner functions that could access variables from the enclosing function. 

Closures keep track of the enclosing function's variables even after it the enclosing function has exited.

Below is a example of a closure:

The function inner_func() has access to var a variable of the enclosing function -.
The enclosing function returns the inner function address.

We use closures mainly for:
  • To hide data.
  • To keep track of a function's environment even after it exits.


Leave as a comment: