Menu

1 / 4

Understanding Scope and Closures in Python

DEV Community·Samiksha Srivastav·6 months ago
#CNBdmegE
#python#programming#webdev#learning#function
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.