I was comfortable with Python scopes pretty quickly.
But when I reached closures, my first reaction was:
“How is this even possible?”
An inner function remembering variables after the outer function has already finished execution felt really confusing at first.
But after understanding how Python handles memory and scope internally, closures finally became much easier to understand.
So here’s the explanation that helped me the most.
First, What is Scope?
Scope simply means:
“Where can a variable be accessed from?”
Python mainly works with different scopes like:
Global scope
Local scope
Enclosing scope
Let’s see a simple example:
Here:
x can be accessed almost everywhere because it is global
y only exists inside the function
Once the function finishes execution, y disappears from memory.
That part is straightforward.
Now Comes Closures
Closures become interesting when:
a function exists inside another function
and the inner function uses variables from the outer function
Example:
At…