DEV Community

Abe Garcia
Abe Garcia

Posted on

Understanding Functional Closures

While learning functional programming in JavaScript and Python, one of the hardest concepts to wrap my head around was the idea of closures. Every explanation I found only served to confuse me more so I decided to write a clear explanation with real code examples.

What Is A Closure?

Inner Functions

The first step to understanding closures is understanding inner functions, i.e., a function declared within another function.

def outer():
    x = 3
    def inner():
        print(x+5)
    inner()

outer() #prints 8 to the console

If we call the function outer(), we can see that it prints out 8. This is because the inner function has access to the variable x, which is in its enclosing scope. So the flow here is outer begins execution and sets the variable x equal to three. The next thing it does is define a function within itself which will print the result of adding 5 to x. It then executes the inner function and returns control to the main program.

Returning The Inner Function

The interesting part happens when we return the inner function from the outer function instead of calling it.

def outer():
    x = 3
    def inner():
        print(x+5)
    return inner

result = outer()  #here we save the returned value of the outer function to a variable

If you were to then print the result variable, this is what gets printed to the console:

<function inner at 0x7f5e8c381668>

Interestingly, we now have a function object assigned to our result variable, which means we can actually call it by adding parentheses to it.
If we call our new result() function, we can see that it still prints out 8. This means that our result function actually remembered what was inside its enclosing scope (the outer function) even though the outer function finished execution long before we ever called our result function. And that's exactly what a closure is! It's the recalling of a variable declared in an enclosing scope even when the program execution has moved on and is no longer in that scope. You could even use the 'del' keyword to delete the outer function and everything inside it, but our result function would still remember the value of x.

Why Use A Closure?

Using a closure can create some form of data privacy, since the main program has no access to anything declared inside the outer function. The only things that could have access to those variables are any functions defined inside the outer function itself. If you're a Python developer though, the most interesting application of closures by far is the concept of decorators.

Top comments (0)