locking - What is the optimal use of a lock with a try ... except in Python 2.7? -
suppose have threading.lock() object want acquire in order use resource. suppose want use try ... except ... clause resource.
there several ways of doing this.
method 1
import threading lock = threading.lock() try: lock: do_stuff1() do_stuff2() except: do_other_stuff() if error occurs during do_stuff1() or do_stuff2(), lock released? or better use 1 of following methods?
method 2
with lock: try: do_stuff1() do_stuff2() except: do_other_stuff() method 3
lock.acquire(): try: do_stuff1() do_stuff2() except: do_other_stuff() finally: lock.release() which method best lock released if error occurs?
the with "context manager" requires __exit__ method, in case ensure that, whatever happens, lock released.
if want handle exceptions occur during whatever you're doing lock, should put try inside with block, i.e. method 2 correct approach. in general, should aim minimise amount of code within try block.
you should specific possible could go wrong; bare except: bad practice (see e.g. "the evils of except"). @ very least (even simple example!) should use except exception:.
Comments
Post a Comment