Python equivalent of golang's defer statement : <p>How would one implement something that works like the <code>defer</code> statement from go in python? </p>

<p>Defer pushes a function call to a stack. When the function containing the defer statement returns, the defered function calls are popped and executed one by one, in the scope that the defer statement was inside in the first place. Defer statements look like function calls, but are not executed until they are popped.</p>

<p>Go example of how it works:</p>

<pre><code>func main() {
    fmt.Println("counting")

    var a *int
    for i := 0; i &lt; 10; i++ {
        a = &amp;i
        defer fmt.Println(*a, i)
    }

    x := 42
    a = &amp;x

    fmt.Println("done")
}
</code></pre>

<p>Outputs: </p>

<pre><code>counting
done
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
0 0
</code></pre>

<p>Go example of a usecase:</p>

<pre><code>var m sync.Mutex
func someFunction() {
    m.Lock()
    defer m.Unlock()
    // Whatever you want, with as many return statements as you want, wherever.
    // Simply forget that you ever locked a mutex, or that you have to remember to release it again.
}
</code></pre>
