go - Python equivalent of golang's defer statement -


how 1 implement works defer statement go in python?

defer pushes function call stack. when function containing defer statement returns, defered function calls popped , executed 1 one, in scope defer statement inside in first place. defer statements function calls, not executed until popped.

go example of how works:

func main() {     fmt.println("counting")      var *int     := 0; < 10; i++ {         = &i         defer fmt.println(*a, i)     }      x := 42     = &x      fmt.println("done") } 

outputs:

counting done 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0 

go example of usecase:

var m sync.mutex func somefunction() {     m.lock()     defer m.unlock()     // whatever want, many return statements want, wherever.     // forget ever locked mutex, or have remember release again. } 

to emulate defer fmt.println(*a, i) example, use contextlib.exitstack:

#!/usr/bin/env python3 contextlib import exitstack functools import partial  print("counting") exitstack() stack:     in range(10):         =         stack.callback(partial(print, a, i))      x = 42     = x     print("done") 

output

counting done 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0 

it easy emulate mutex case:

def some_function(lock=lock()):     lock:         # whatever 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -