Saturday 24 December 2016

What is Closure in python?

A closure is a function object.A closure remembers values from the enclosing lexical scope even when the program is no longer in the enclosing scope.
Inner function in a nested function can be called as a closure,but not always.
A closure occurs when a function has access to local variables from an enclosing function that has completed execution.
Example:def make_out_love(x):
                      def love():
                            print(x)
                      return love
                love = make_out_love('Tonight We are making love')
                love()

A nested function is not closure if:
1.Nested functions dont access variables that are local to enclosing scopes.
2.If Nested functions are executed outside the scope.

Example:def make_out_love(x):
                           def love(x=x):
                                 print(x)
                           return love

              love = make_out_love('Tonight We are making love')
              love()

1.Closures are functions that inherit variables from enclosing environment.
2.Function should use free variables in order to be a closure
3.The attribute __closure__ saves the free variables.
4.Every function in python has closure attributes but it does not save any content if there are no free variables.
5.The closure attribute(__closure__) returns a tuple of cell objects which contain details of the variables defined in the enclosing scope.
Note:Every Function has a __closure__ attribute,if there is no data for __closure__ attribute  it is assigned None.

Why to and who use Closures?
1.Decorators in python makes extensive use of closures.