1
+ # Closure :
2
+ # Before seeing what a closure is,
3
+ # we have to first understand what nested functions and non-local variables are.
4
+
5
+ # What are Python Closures
6
+
7
+ # A Closure in Python is a function object that remembers values in enclosing scopes even
8
+ # if they are not present in memory.
9
+
10
+ # It is a record that stores a function together with an environment: a mapping associating each free variable
11
+ # of the function (variables that are used locally but defined in an enclosing scope) with the value
12
+ # or reference to which the name was bound when the closure was created.
13
+ # A closure—unlike a plain function—allows the function to access those captured variables
14
+ # through the closure’s copies of their values or references,
15
+ # even when the function is invoked outside their scope.
16
+
17
+
18
+ # example 1: This is not closure
19
+ def outerFunction ():
20
+ text = 'hi'
21
+ def innerFunction ():
22
+ # text is free variable
23
+ print (text ) # text is free variable it can be access inside a innerfunction
24
+
25
+ # Note we are returning function
26
+ # WITH parenthesis
27
+ return innerFunction () # returning and executing innerfunction
28
+
29
+
30
+ outerFunction ()
31
+
32
+ # Example 2:
33
+ # Python program to illustrate
34
+ # closures
35
+ def outerFunction ():
36
+ text = 'Hey'
37
+
38
+ def innerFunction ():
39
+ # text is free variable
40
+ print (text )
41
+
42
+ # Note we are returning function
43
+ # WITHOUT parenthesis it will not execute nothing
44
+ return innerFunction
45
+
46
+ myFunction = outerFunction () # It will execute everything inside a outerfunction and return innerFunction
47
+ print (myFunction ) # myFunction is a function now because we only returned not execute the innerfunction
48
+ print (myFunction .__name__ ) # display inner function name on it
49
+ myFunction () # Hey
50
+ myFunction () # Hey
51
+ myFunction () # Hey
52
+
53
+ # It print out message. we are done with executing outer function.
54
+ # but the inner function has still has access to that text variable that is it printing out.
55
+ # Thats what closure is In simple terms a closure is a inner function that remembers and has
56
+ # access to variable in the local scope in which it was created even after the outer function
57
+ # has finished executing
58
+
59
+ # Example 3: Add parameter to a function
60
+ def outerFunction (msg ):
61
+ message = msg
62
+ def innerFunction ():
63
+ print (message )
64
+ return innerFunction
65
+
66
+ hi_Function = outerFunction ('Hi!' )
67
+ hello_Function = outerFunction ('Hello!' )
68
+ hi_Function () # Hi!
69
+ hello_Function () # Hello!
70
+
71
+ # One thing you must notice that we stil innerfunction still doesnot take any argument
72
+ # to execute this function only need paranthesis.
73
+ # when call this each function print is own values
74
+ # that closure closes over the free variable from their environment
75
+ # In this case message would be that free variable.
76
+
77
+
78
+ # Example 3:
79
+
80
+ import logging
81
+ logging .basicConfig (filename = 'example.log' ,level = logging .INFO ) # create logging file
82
+
83
+ def logger (func ):
84
+ def logfun (* args ): # *args= any no of arguments can be passed
85
+ logging .info ('running"{}"with arguments {}' .format (func .__name__ ,args )) # print loggin info in example.log file on it
86
+ print (func (* args )) # call those func name passed in outer function and pass the inner function *args values
87
+ return logfun # it only return the inner function not executed
88
+
89
+ def add (x ,y ):
90
+ return x + y
91
+
92
+ def sub (x ,y ):
93
+ return x - y
94
+
95
+ add_log = logger (add )# outer function executes and pass the argument
96
+ sub_log = logger (sub )
97
+
98
+ add_log (10 ,20 ) # inner function still have access to the outer function after execution it remember the inner function
99
+ add_log (3 ,3 ) # so it can easy to access the free variabe on it
100
+
101
+ sub_log (20 ,10 )
102
+ sub_log (5 ,2 )
0 commit comments