1.

What are Closures in Python?

Answer»

Python allows a function to be defined inside another function. Such functions are called nested functions. In such case, a certain variable is located in the order of local, outer, global and lastly built-in namespace order. The inner function can access variable declared in nonlocal scope.

>>> DEF outer(): DATA=10 def inner(): PRINT (data) inner() >>> outer() 10

Whereas the inner function is able to access the outer scope, inner function is able to use variables in the outer scope through closures. Closures maintain references to objects from the earlier scope. 

A closure is a nested function object that REMEMBERS values in ENCLOSING scopes even if they are not present in memory.

Following criteria must be met to create a closure in Python:

  • We must have a nested function (function inside a function).
  • The nested function must refer to a value defined in the enclosing function.
  • The enclosing function must return the nested function.

Following code is an example of closure.

>>> def outer(): data=10 def inner(): print (data) return inner >>> closure=outer() >>> closure() 10


Discussion

No Comment Found