contextmanager

How should I return interesting values from a with-statement?

Is there a better way than using globals to get interesting values from a context manager? @contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() errorCount += 1 else: storage.store.commit() successCount += 1 Other...

Finding Functions Defined in a with: Block

Here's some code from Richard Jones' Blog: with gui.vertical: text = gui.label('hello!') items = gui.selection(['one', 'two', 'three']) with gui.button('click me!'): def on_click(): text.value = items.value text.foreground = red My question is: how the heck did he do this? How can the conte...

python: create a "with" block on several context managers

Suppose you have three objects you acquire via context manager, for instance A lock, a db connection and an ip socket. You can acquire them by: with lock: with db_con: with socket: #do stuff But is there a way to do it in one block? something like with lock,db_con,socket: #do stuff Furthermore, is it possib...

is a decorator in python exactly the same as calling a function on a function?

I thought that doing @f def g(): print 'hello' is exactly the same as def g(): print 'hello' g=f(g) But, I had this code, that uses contextlib.contextmanager: @contextlib.contextmanager def f(): print 1 yield print 2 with f: print 3 which works and yields 1 3 2 And when I tried to change it into def f()...

simplifying threading in python

I am looking for a way to ease my threaded code. There are a lot of places in my code where I do something like: for arg in array: t=Thread(lambda:myFunction(arg)) t.start() i.e running the same function, each time for different parameters, in threads. This is of course a simplified version of the real code, and usually the co...