Python – Closure

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:

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.

That’s all! Hope you found what you were looking for! 🙂

Tagged with: , ,