In this article I am planning to give an answer of the following two questions:
- What is a closure?
- A closure is a function, inheriting variables from enclosing environment. Operationally, a closure is a record storing a function together with an environment…
- Where is it used in Python?
- Ok, even reading the first two sentences from the “closure” definition 2-3 times would probably not give you an idea about closure. Thus, take a look at the examples.
Example 1 – greet_in_the_afternoon = say_hello(False)
Imagine that you need a function, saying “Good morning”, if it is before 12:00 and “Good afternoon” otherwise. Sounds rather trivial, a simple condition and that is it. However, imagine actually wanting to save the function, returning “Good morning” and “Good afternoon” and add some name to it, so the function actually returns “Good morning Mr. Reader” or Good afternoon Mr. Reader”, just by giving the “Mr. Reader” as a parameter. The following example does exactly this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def say_hello(before_noon): if before_noon: def greet_explicitly(name): return f'Good morning, {name}!' else: def greet_explicitly(name): return f'Good afternoon, {name} :) ' return greet_explicitly greet_in_the_morning = say_hello(True) print(greet_in_the_morning("Mr. Vitosh")) print(greet_in_the_morning("Mr. Doynov")) greet_in_the_afternoon = say_hello(False) print(greet_in_the_afternoon("Mrs. Reader.")) print(greet_in_the_afternoon("Ms. Reader of my blog!")) |
The result is interesting. Pay attention to the appearance of the “:)” sign:
Example 2 – times_8_times_9 = times_8(9)
This example is rather more explanatory and probably easier to understand. Still, I have decided to give it as a second one. First you need a function, which multiplies 2 numbers. But, to make it more interesting, you create a function, that only knows the first number to be multiplied. Imagine the first number is 5, then you return the function times_5(x). And whenever you call times_5(x) it will return the result of x * 5 ! Rather self explanatory, if you ask me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def times(n): def multiply(m): return n * m return multiply times_8 = times(8) times_8_times_9 = times_8(9) print(times_8_times_9) #72 times_5 = times(5) times_5_times_3 = times_5(3) #15 print(times_5_times_3) for i in range(100): print(times_5(i)) #looping 0 to 500 with step 5 |
That’s all! Hope you found what you were looking for! 🙂