What is Closure? How to Implement it in Python?

Aykhan Nazimzada
5 min readOct 11, 2020

--

In this article, we will talk about programming term “Closure”, answer the questions what closure is, and how to implement them. As an illustration, we will examine the closure in Python. So, if you are not familiar with Python, no worries. What’s important is to take away the concept of a closure and not the specific syntax of any one language. Only prerequisite is to understand functions in programming languages and scoping. So, to shortly recap, functions allow us to treat functions like any other object so for example we can pass functions as an argument to another function we can return functions and we can assign functions to variables. And term “scope” refers to the visibility of variables and methods in one part of a program to another part of that program. These information are crucial to comprehend the concept of “Closure”.

So, what exactly closure is? According to Wikipedia, “Closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function (variables that are used locally but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.” With my own words, closure is a function that remembers its outer variables and can access them.

I know it sounds complex and hard to understand. We will move step by step, and at the end, we will clearly understand every sentence of definition mentioned above. In programming languages, best explanation is through code of example. Therefore, let’s look at few examples written in Python.

You can see here, when I call outer function (‘outer_func’) that it executes the function and doesn’t take any parameters. What the function does, it assigns string “Hello World!” to variable ‘example’. Then, we have an inner function (‘inner_func’) which also doesn’t take any parameters. It just prints the variable ‘example’, assigned by outer function. If you noticed that our inner function accessed the variable declared by outer function. This type of variable is called free variable. Free variables are simply the variables that are neither locally declared nor passed as parameter. After defining inner function, in the body of outer function, we return inner function (As we want to execute also inner function when we call outer function). Once again, when we execute ‘outer_func’, it assigns a string to a variable then returns the ‘inner_func’, and inner function prints that string. As you see, output of program is “Hello World!”.

Now, let’s play a little around code. Instead of returning this inner function and then executing it, let’s just return the function without executing. We can do this as follows.

To achieve this, in the return part of the ‘outer_func’, we remove the parenthesis after ‘inner_func’. Output of the program is nothing when we call outer function. Obviously, it assigns the string to variable and return unexecuted inner function. But what actually does it?

In this piece of code, I assigned to variable ‘var_funct’ what returns from my outer function which unexecuted ‘inner_func’. After printing that variable, we see some info about our inner function, its outer function and address of it.

Now the question arises. How to execute our inner function using this variable?

Finally, we reach to the point where we will clearly get the concept of closure. To execute the inner function with ‘var_func’, we simply put parenthesis to the end. Now, inner function executed, and output is again “Hello World!”. Keep in mind that with saying “var_func = outer_func()”, we already executed the outer function. In ‘var_func’, we have address of the inner function. When writing “var_func()”, outer function is not going to be executed again. We just execute the inner function. This is exactly where we face with closure. Because we’re done with the execution of our outer function but the inner function that we returned still has access to that example variable that it’s printing out. That’s what a closure is so in simple terms. To summarize what we learned about closure so far, closure is an inner function that remembers and has access to variables in the local scope in which it was created even after the outer function has finished executing.

So far, our functions were not taking any parameters. What if they had parameters? So, let’s try to kill our curiosity.

Here, I’m passing parameter to my outer function called ‘var_parameter’. Then, I assign it to my example variable which I used and will use in my inner function. I don’t make any changes on my inner function and still outer function returns unexecuted inner function. Now, let’s call outer functions 2 times and assign to 2 variables (‘var_func1’ and ‘var_func2’). In ‘var_func1’, we pass “Hello World!” and “GoodBye World!” for ‘var_func2’. In this place, note that inner function does not take any parameters, so we can execute it with calling ‘var_func1()’ and ‘var_func2()’ with adding empty parenthesis at the end. After executions, output of program is “Hello World!” and “GoodBye World!” correspondingly.

What is interesting is that each of these functions (‘var_func1()’ and ‘var_func2()’) remembers the value of their own ‘example’ variable. Now, another definition of closure comes. “Closure closes over the free variables from their environment”. In this case, ‘example’ is our free variable. The purpose of closures is simply to preserve state; hence the name closure — it closes over state.

In this article, I tried to explain programming term “closure” through code of examples written in Python. Closure is not a data type & structure. It is a concept or methodology. So, it can be implemented in variety of programming languages. I preferred Python as an example where closures are mostly used in JavaScript. You can consider this paper as an introduction to closure where applications of closure is wide and deep.

--

--

No responses yet