Code Explanation:
1. ๐ฆ Import ExitStack
from contextlib import ExitStack
ExitStack is provided by Python's contextlib module.
It allows us to register multiple cleanup actions that should execute when the with block finishes.
The important behavior here is:
Callbacks execute in reverse order of registration — LIFO (Last In, First Out).
2. ๐ Create an Empty List
x = []
Initially:
x = []
This list will store values as they are appended.
3. ๐ช Create the ExitStack
with ExitStack() as s:
An ExitStack object is created and assigned to s.
The callbacks registered inside this block will normally execute when Python leaves the with block.
At this point:
Callbacks: none
x = []
4. ➕ Register the First Callback
s.callback(x.append, 1)
This does not immediately execute:
x.append(1)
Instead, it registers it as a callback to be executed when the ExitStack closes.
So conceptually:
Callback stack:
[append(1)]
Still:
x = []
5. ➕ Register the Second Callback
s.callback(x.append, 2)
Again, x.append(2) is registered, not executed immediately.
Now the callback stack is:
First → append(1)
Second → append(2)
The most recently registered callback is append(2).
6. ⚡ Normal append() Executes Immediately
x.append(3)
This is different from s.callback().
This line directly modifies the list:
x = [3]
The callback stack is still:
append(1)
append(2)
7. ๐ช Leaving the with Block
When Python reaches the end of:
with ExitStack() as s:
the ExitStack closes automatically.
Now the registered callbacks execute.
But they execute in LIFO order:
append(2)
↓
append(1)
So:
x = [3]
↓
append(2)
↓
x = [3, 2]
↓
append(1)
↓
x = [3, 2, 1]
8. ๐จ️ Print the List
print(x)
By this point:
x = [3, 2, 1]
Therefore:
✅ Final Output
[3, 2, 1]

0 Comments:
Post a Comment