Python Closures: Magic of Enclosed Functions

Understand and harness the power of Closure in Python — the key to writing efficient and maintainable code.

Arun Suresh Kumar
PythonIQ

--

Photo by Patrick Tomasso on Unsplash

I have seen a lot of senior python developers and architects struggle with the concept of closure. So if you have to read this article couple of times to grasp it, it is normal. It is an advanced topic, but not that difficult to grasp if you try to understand why we use Closure.

What is closure?

Let’s start with the basics. Closure is just a function object that remembers values in its enclosing scope even if they are not present in memory anymore. It’s a record that stores a function together with an environment. That means it stores a mapping associating each free variable of the function (variables that are used locally and defined in enclosing scope) with the value or reference to which the name was bound when the closure was created.

This might still sound intimidating but I will explain with examples. Just keep in mind that closure allows the function to access the captured variables through the closure’s reference to them, even when the function is invoked outside their scope.

Let’s see an example which explains how closure is created when a nested function references a…

--

--

Arun Suresh Kumar
PythonIQ

Technology enthusiast, Python developer, Angular artist, Corporate leader | https://www.linkedin.com/in/yeaske/ | Amateur chef ➜ https://instagr.am/yeaske/