How to implement retrying a lock tidily in Python?
davea at ieee.org
Sun Oct 17 23:19:56 CEST 2010
On 2:59 PM, tinnews at isbd.co.uk wrote:
> I'm writing some code that writes to a mbox file and want to retry
> locking the mbox file a few times before giving up. I can't see a
> really tidy way to implement this.
> Currently I have something like:-
> dest = mailbox.mbox(mbName, factory=None)
> for tries in xrange(3):
> # Do some stuff to the mbox file
> break # done what we need, carry on
> except mailbox.ExternalClashError:
> log("Destination locked, try " + str(tries))
> # and try again
> ... but this doesn't really work 'nicely' because the break after
> dest.unlock() takes me to the same place as running out of the number
> of tries in the for loop. I need a way to handle the case where we
> run out of tries (and *haven't* done what we needed to do) separately
> from the case where it worked OK.
> I can see all sorts of messy ways to handle this with a flag of some
> sort but is there a proper elegant way of doing it?
The usual idiom for telling whether you ever finished a loop is to use
the else: clause. Else is only executed if break was never executed.
do ... one failure
...None of the loops succeeded
In your case you're using try/except, rather than if/else, but the outer
mechanism still holds.
More information about the Python-list